Is there a way to add an alias from the command line without directly editing the bash_aliases file? To clarify, how can I make a bash script do it without having to enter something along the lines of
nano bash_aliases to add them?
Assuming you are using
bash_aliases (it is not necessary, you can also have aliases defined in
.bashrc among other places), you can simply add a line to the file:
printf "alias foo='bar'" >> ~/.bash_aliases
Alternatively, if you only want this alias for the current session, use the alias command directly:
Bash does not allow aliases to be expanded (to work) in scripts by default, you will need to activate the
#!/usr/bin/env bash alias foo='echo "It works!"' echo " Alias defined, attempting to use without expand_aliases" foo shopt -s expand_aliases echo " Attempting to use with expand_aliases" foo
If I run the script above, the alias
foo will only work after I have activated the
$ a.sh Alias defined, attempting to use without expand_aliases /home/terdon/scripts/a.sh: line 5: foo: command not found Attempting to use with expand_aliases It works!
You can also use HEREDOCS to add multiple lines as well:
( cat <<EOF alias ali1='cmds1...' alias ali2='cmds2...' EOF ) >> ~/bash_aliases
The above can be copy pasted into a shell.
$ more ~/bash_aliases alias ali1='cmds1...' alias ali2='cmds2...'