0

I thought I will write a bash script to set the alias I frequently use, and also to change the command promt.

Below is my script.

#!/bin/bash
# Make useful aliases
alias c='clear'
alias p='pwd'
alias d='pwd'
alias l='ls -l'
alias clp='clear;pwd'
# Prompt
PS1='unix % '
# Echo to check if script runing
echo 'Hello world'

But when I run this script(after giving it execute permission) the alias are not added. Neither is the prompt updated with the value given for PS1. Nonetheless it echoes Hello world so it looks like the script is running.

user $ ./myEnv.sh 
Hello world
user $ d
d: command not found
user $

Where is the mistake ?

sps
  • 1,436

3 Answers3

3

Easy the script created those variables in his own environment. Then when exiting, this specific environment is destroyed and you return to the parent shell's environment where those variables are not set like you want.

Instead of executing it, you should source it like . myEnv.sh

netmonk
  • 1,870
2

The script will create the alias in its own instance. The alias will not be available in another or the parent bash instance. Also the prompt is changed only in that specific bash instance.

magor
  • 3,752
  • 2
  • 13
  • 28
2

As others have said, you should source a script if you want things like aliases and changed environment variables to have an effect.

However, the downside of that is that while you can execute a script in your path, you can't source a script in that manner; this would mean that every time you want to include your aliases, you'd have to specify a full path. This can be somewhat annoying.

To avoid that, you'll have to use ~/.bashrc. At startup, when running interactively, the bash shell will source that file automatically, so if you define your aliases in that file, they will be available in all (newly-started) shells from that point forward.

If you don't want the aliases to always be available, then you can create a function in your ~/.bashrc:

addaliases() {
    alias c='clear'
    alias p='pwd'
    # ... and so on
}

Now, next time you start bash, you can run addaliases from the command line, and then the aliases will be added.

If you don't use bash but use some other shell, then obviously you shouldn't put this in ~/.bashrc, but in another file; which one exactly depends on the exact shell that you're using.

  • thank you for the suggestion. Actually I have to work in a system where i DONT have permission to change .bashrc file. I was tired of putting up thiese aliases everytime manually, so i thought i would write a scripte so that it will be like only running one command. The function idea in cool, will start using it in my personal pc. – sps Oct 09 '15 at 10:39