4
4
460s2016-04-25 10:33:09
bash
460s, 2016-04-25 10:33:09

Update list of alias from shell script. How?

I add an alias using the shell script:
echo "alias sc='echo 21'" >> ~/.bashrc
After that, you should run the bashrc script itself so that the changes take effect before the reboot.
If executed:
. ~/.bashrc
Nothing will happen, because the file will simply be included in the script.
Actually the question is how to update the list of aliases from the script?
alias alias_command_name='commands'
It will not help, because it will only work for the current session.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Danil Biryukov-Romanov, 2016-04-25
@urtow

You shouldn't use Alias ​​in scripts - alias is just a shorthand. For the specified task in bash, you need to use functions, you can read about creating functions here - www.bash-scripting.ru/abs/chunks/ch23.html
For this example, add this to .bashrc:

function sc(){
  echo 21
}

Now this function is available to us in scripts:
#!/bin/bash
. ~/.bashrc
sc

By running this script, we will get output 21. The most convenient thing is that in an interactive session everything will work exactly the same - since the function is specified in bashrc after restarting the interactive session, we can use the sc function like any bash interpreter command

V
Vlad Zhivotnev, 2016-04-25
@inkvizitor68sl

If we omit the question of "correctness", then you need to poke the following at the beginning of the script:
shopt -s expand_aliases
In fact, aliases are sometimes needed, for example, for this:
alias sqlite_exec="flock -w 60 /tmp/mon.lock /usr/bin/ sqlite3 ${DATABASE}"
You can't achieve a function so that you can write sqlite_exec ${query}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question