Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do create an alias in shell scripts? [duplicate]

Tags:

alias

bash

shell

Definin an alias on Linux system is very simple.

From the following example we see that: the I_am_only_ls_alias alias command gives us the output as ls command

 # alias I_am_only_ls_alias=ls
 # I_am_only_ls_alias

Output:

file   file1

But when I trying to do the same in bash script (define alias I_am_only_ls_alias), I get I_am_only_ls_alias: command not found.

Example of my bash script:

alias_test.bash

#!/bin/bash

alias I_am_only_ls_alias=ls

I_am_only_ls_alias

Run the bash script - alias_test.bash

/tmp/alias_test.bash

Output:

/tmp/: line 88: I_am_only_ls_alias: command not found

So, first I want to ask:

Why doesn't bash recognize the command I_am_only_ls_alias as an alias?

And what do I need to do in order to define aliases inside a bash script? Is it possible?

like image 269
maihabunash Avatar asked Jun 05 '14 07:06

maihabunash


People also ask

Can I create an alias in a bash script?

The Bash alias command allows a string to be substituted when it is used as the first word of a command line. The shell maintains a list of aliases that may be set and unset with the Bash alias and unalias builtin commands.

Can you use alias in shell script?

An alias is a way of shortening a command. (They are only used in interactive shells and not in scripts — this is one of the very few differences between a script and an interactive shell.)

What is $1 and $2 in shell script?

These are positional arguments of the script. Executing ./script.sh Hello World. Will make $0 = ./script.sh $1 = Hello $2 = World. Note. If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh .


1 Answers

From the bash man page:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

So this should work:

#!/bin/bash
shopt -s expand_aliases
alias I_am_only_ls_alias=ls
I_am_only_ls_alias

Scripts usually use functions, not aliases.

like image 151
Barmar Avatar answered Sep 18 '22 12:09

Barmar