My alias defined in a sample shell script is not working. And I am new to Linux Shell Scripting. Below is the sample shell file
#!/bin/sh echo "Setting Sample aliases ..." alias xyz="cd /home/usr/src/xyz" echo "Setting done ..."
On executing this script, I can see the echo messages. But if I execute the alias command, I see the below error
xyz: command not found
am I missing something ?
Your alias is well defined, but you have to store it in ~/. bashrc , not in a shell script. Add it to that file and then source it with . . bashrc - it will load the file so that alias will be possible to use.
How to set a Bash Alias? You can define a new alias by using the Bash command alias [alias_name]="[command]" . A Bash alias name cannot contain the characters / , $ , `` , = and any of the shell metacharacters or quoting characters. for the changes to take effect in your current terminal session.
In Linux, an alias is a shortcut that references a command. An alias replaces a string that invokes a command in the Linux shell with another user-defined string. Aliases are mostly used to replace long commands, improving efficiency and avoiding potential spelling errors.
$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1) $9 is the ninth argument.
source your script, don't execute it like ./foo.sh
or sh foo.sh
If you execute your script like that, it is running in sub-shell, not your current.
source foo.sh
would work for you.
You need to set a specific option to do so, expand_aliases
:
shopt -s expand_aliases
Exemple:
# With option $ cat a #!/bin/bash shopt -s expand_aliases alias a="echo b" type a a $ ./a a is aliased to 'echo b' b # Without option $ cat a #!/bin/bash alias a="echo b" type a a $ ./a ./a: line 3: type: a: not found ./a: line 4: a: command not found
cf: https://unix.stackexchange.com/a/1498/27031 and https://askubuntu.com/a/98786/127746
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With