Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using alias in shell script? [duplicate]

Tags:

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 ?

like image 871
Narain Avatar asked Apr 12 '13 09:04

Narain


People also ask

Can you use alias in shell script?

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.

Can you set an alias in a bash script?

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.

What is alias in shell script?

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.

What is $1 and $2 in shell script?

$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.


2 Answers

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.

like image 58
Kent Avatar answered Oct 02 '22 19:10

Kent


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

like image 30
AdrieanKhisbe Avatar answered Oct 02 '22 19:10

AdrieanKhisbe