45 Examples of Variables and Arrays in Shell Script

  10 mins read  

45 Examples of Variables and Arrays in Shell Script

1 - Create a variable, ${var} is the same as $var, but not ambiguous.

echo $var

2 - Return string length

echo ${#var}

3 - Execute the contents of $var (same as ‘eval $$var’)

echo ${!var}

4 - Returns variable names beginning with ‘U’

echo ${!U*}

5 - Returns the text from position 7

echo ${var:7}

6 - Returns 8 characters from position 11

echo ${var:11:8}

7 - Cut ‘http://’ from beginning of string

echo ${var#http://}

8 - Cut ‘.com.br/’ from end of string

echo ${var%.com.br/}

9 - Replaces ‘terminalroot’ with ‘aurelio’ once

echo ${var/terminalroot/aurelio} 

10 - Replaces ‘o’ with ‘O’, always

echo ${var//o/O}

11 - If string starts with ‘http’, replace ‘http’ with ‘Site’

echo ${var/#http/Site}

12 - If string ends with ‘st’, replace ‘st’ with ‘STING’

echo ${var2/%st/STING}

13 - ”“ (double quotation marks) protect a string, but recognize $, \ and ` as specials

echo "$var"

14 - ’‘ (single quotes) protects a string, but recognizes $, \ and ` as specials

echo '$var'

15 - $’…‘ (dollar sign before single quotes) protects a string completely, but interprets \n, \t, \a, etc.

echo $'$var\n'

16 - ... (between crases) Execute commands in a subshell, returning the result

echo `ls`
Desktop Documents Downloads Images Templates Music Public Videos

17 - Execute commands on a subshell

Desktop Documents Downloads Images Templates Music Public Videos

18 - Execute commands on a subshell, returning the result

echo $(ls)
Desktop Documents Downloads Images Templates Music Public Videos

19 - Tests an arithmetic operation, returning 0 or 1


20 - Returns the result of an arithmetic operation.

echo $((11-9))

21 - Tests an expression, returning 0 or 1 (alias of command ‘test’)

[[ $var ]] && echo 'Its bigger'
Its bigger
22 - Tests an expression, returning 0 or 1 (can use && and ** ** )
[[ $var ]] && echo 'Is there this variable'
Is there this variable

23 - Special Variables

VariablePositional Parameters
$0Parameter Number 0 (Name of Command or Function)
$1Parameter Number 1 (from command line or function)
...Parameter number N …
$9Parameter Number 9 (from command line or function)
${10}Parameter Number 10 (from command line or function)
...Parameter number NN …
$#Total number of command line or function parameters
$*All parameters as a single string
$@All parameters, such as multiple protected strings
$$PID number of current process (from script itself)
$!PID number of last background job
$_Last argument of last command executed
$?Return code from last command executed

25 - Special escapes to use at prompt (PS1)

EscapeReminderExpands to …
\aAlertAlert (beep)
\dDateDate in “Weekday Month Day” format (Sat Jan 15)
\eEscapeEsc Character
\hHostnameMachine Name Without Domain (dhcp11)
\HHostnameFull Machine Name (dhcp11.company)
\jJobsNumber of Active Jobs
\lTtyCurrent Terminal Name (ttyp1)
\rReturnReturn by car
\sShellName of the shell (basename $ 0)
\tTimeTime in 24-hour format HH: MM: SS
\TTime12-hour format HH: MM: SS
\@AtTime in 12-hour format HH: MM am/pm
\AAtTime in 24-hour format HH:MM
\uUserCurrent user login
\vVersionBash Version (2.00)
\VVersionBash Version Subversion (2.00.0)
\wWorking DirCurrent directory, full path ($PWD)
\WWorking DirCurrent directory, only the last one (basename $PWD)
\!History icoCurrent command number in history
\#NumberCurrent command number
\$ID >Show “#” if root, “$” if normal user
\nnnOctalCharacter whose octal is nnn
\\BackslashBackslash \ literal
\[EscapesStarts a sequence of escapes (color coded type)
\]EscapesEnds an escape sequence

27 - Formatters of the date Command

%aAbbreviated Weekday Name (Sun..Sab)
%AName of the day of the week (Sunday..Saturday)
%bAbbreviated Month Name (Jan. Dec)
%BName of the month (January.December)
%cComplete date (Sat Nov 04 12:02:33 EST 1989)
%yYear (two digits)
%YYear (four digits)
%mMonth (01..12)
%dDay (01..31)
%jDay of the year (001..366)
%HHours (00..23)
%MMinutes (00..59)
%SSeconds (00..60)
%sSeconds since January 1, 1970
%%A % literal
%tOne TAB
%nA line break

28 - Printf Command Formatters

%dDecimal number
%oOctal Number
%xHexadecimal Number (a-f)
%XHexadecimal Number (A-F)
%fFloating-point number
%eNumber in scientific notation (e + 1)
%ENumber in scientific notation (E + 1)

29 - To know all local variables, execute


or, and open txt to see later

set > VariablesLocations.txt

30 - Global Variables, to know all global variables, execute




31 - To assign a value to a local variable

echo $LINUX

32 - check if the variable created in the previous item appears in the list of local variables

set | grep LINUX

33 - Now let’s make this local variable a global variable.

export LINUX
env | grep LINUX

34 - Delete a ‘local environment variable’ from memory using unset command

unset LINUX
echo $LINUX

35 - Create an alias (nickname for a command or program), you can still include it in your ~/.bashrc

alias list='ls -la color=auto'

36 - Destroying an aliase

unalias list

37 - Verify all commands entered


run command by his number in history


execute last command typed


they stay in bash_history

cat ~/.bash_history

clear history

history -c

38 - Command Line Interpreters

$ - Shell of an normal user;

# - Superuser shell root (administrator)

Check of Available Shells

cat /etc/shells

Variable that shows the SHELL you use

echo $SHELL

39 - Creating an Array (Array) “Variable Set”

DISTROS=("Debian" "Trisquel" "Ubuntu" "RedHat")

If you print the DISTROS Array as a variable, it prints variable 0, the array displays the variables contained in it starting at 0 (zero), so it would be the same as printing at ${DISTROS[0]}


40 - Print element 1 of array DISTROSS

echo ${DISTROS[1]}

41 - You can also create an array by inserting element one at a time.


42 - Change element 2 of array DISTROSS

DISTROS[2]="Linux Mint"
echo ${DISTROS[2]}
Linux Mint

43 - Display Element 2 Distro to End

echo ${DISTROS[@]:2} 
Ubuntu RedHat

44 - This displays the elements starting at position 1 followed by two more elements consecutive to position 1

echo ${DISTROS[@]:1:2} 
Trisquel Ubuntu

45 - Know how many elements the array has DISTROSS

echo ${#DISTROS[@]}