hvn-network

My Blog List

Friday, September 16, 2016

[Shell script] Special characters

1. #

 # comment character (#)
 echo "Acomment will follow."#comment here
 
 echo "Acomment will follow." #comment here // need a space
  
 echo $(( 2#101011 )) # base conversion, not a comment

2. ,

# comma operator (,): links together a series of arithmetic operations. All are evaluated, but only the last one is returned.
let "t= ((a = 9, 15 / 3))"
echo "a = $a, t = $t"
for file in /{,usr}bin/ ... # blabla -> search file in /bin directory and /usr/bin directory

3. ${}

# parameter substitution: (${}): may be used for variable concatenation:
ourpath=${PWD}/test_path/
filename=quang
ourfile=${filename}_file.txt
echo "path1: $ourpath"
echo "file1: $ourfile"

ourpath2=$PWD/test_path2/
ourfile2=$filename_file2.txt
echo "path2: $ourpath2"
echo "file2: $ourfile2"

4. $'..'

# quoted string expansion: ($'..')
quote=$'\042'
pound=$'\043'
echo -e "quote: $quote\npound: $pound\n"

5.

# Positional parameters (used when pass arguments from command line)
echo "positional variables: $*" # all of the positional parameters
echo "$@"  

6. $?

# exit status variable
echo "Exit status variable: $?"

7. $$

# process ID variable
echo "Process id: $$"

8. ()

# Group of commands
(a=hello; echo "Sub shell: a = $a, b = $b")
echo "Main cell: a = $a"
# Array initialization
arr=(e1 e2 e3)
echo "arr(0) = ${arr[1]}"

9. {}

# example using block of code:
File=file1

{
    read line1
    read line2
} < $File

10. [[..]]

# test condition ([[..]])
file=/etc/passwd
cur_file=$PWD/file2
if [ -e $file ]; then
    echo "Password file exists"
fi
if [ -e $file || -e cur_file ]; then  # can not use || operator in this condition test.
    echo "Password file or $file2 exists"
fi
if [ $a -eq $b ]; then  
    echo "compare a vs b using -eq operator"
else
    echo "a != b"
fi

if [[ -f $file ]]; then # using [[..]], rather than [..] can prevent many logic errors in scripts, Ex. $$, ||, <, > operators
    echo "Password file exists"
fi
if [[ -f $file || -f $cur_file ]]; then # using [[..]], rather than [..] can prevent many logic errors in scripts, Ex. $$, ||, <, > operators
    echo "Password file or $file2 exists"
fi

# Note: following an if, neither the test command nor the test brackets ([], [[]]) are strictly neccessary, the if COMMAND struct returns the exit status of COMMAND
# Similarly, a condition whithin test brackets may stand alone without an if.
[$a -eq $b]
    echo "a==b"

11.

# integer expansion
a=3
b=7
echo $[$a + $b]
echo $(($a + $b))
echo `expr $a + $b`
echo $(expr $a + $b)

12.

//your code

13.

//your code

14.

//your code

15.

//your code

No comments:

Post a Comment