Saturday, May 24, 2014

Unix Shell Command Substitution(1)

1. Use ` ` for command substitution
./script:
`ls script*` represent the output of the command here, which is a list of all file names. And for loop will use space as default separator to assign each file name to variable i.
 #! /bin/bash  

 for i in `ls script*`  
 do  
   echo $i  
 done  

terminal:
 aubinxia@aubinxia-fastdev:~/Desktop/xxdev$ ./script_1  
 script~  
 script!  
 script_1  
 script_1~  
 script_2  
 script_2~  

2. Nested Command Substitution
./script:
 #! /bin/bash  

 #echo [] is nested inside another echo  
 echo { `echo []` }  
 #output:  
 #{ [] }  

 #trying to insert another "echo ()" inside the 2nd level  
 #echo, but this is wrong!  
 echo { `echo [ `echo ()` ]` }  

 #correct way:  
 #we need to escape the "`" and "()". The reason to escape "`"  
 #is: it is nested in another command substitution  
 #The reason to escape () is: we need them to be interpreted   
 #literally by the shell  
 echo { `echo [ \`echo \(\)\` ]` }  
 #output:  
 #{ [ () ] }  

 #trying to insert another "echo hello" inside. Following three  
 #ways are all wrong. First one, "echo hello" is taken as string  
 #instead of command substitution  
 #Second one, syntax error  
 #Third one, still syntax error. The point is: the second "\`" is   
 #combined with first "\`" to form a command, which totally messed up  
 #the command.  
 echo { `echo [ \`echo \( echo hello \)\` ]` }  
 #output: { [ ( echo hello ) ] }  
 echo { `echo [ \`echo \( `echo hello` \)\` ]` } #error  
 echo { `echo [ \`echo \( \`echo hello \` \)\` ]` } #error  

3. Nested Command Substitution and double quote
./script_1:
 #! /bin/bash  
 echo "outer outer"  
 #output: outer outer  

 echo "outer --`echo []`-- outer"  
 #output:  
 #outer --[]-- outer  

 #Explanation:  
 #\`echo \"Hello world\"\` is the inner level, which is executed firstly  
 #double quote is used to interpret string "Hello world"  
 #then: `echo [\`echo \"Hello world\"\`]` is run secondly, but at this time  
 #it is already transformed into: `echo [Hello world]`  
 #Finally, the outside echo is run.  
 echo "outer --`echo [\`echo \"Hello world\"\`]`-- outer"  
 #output:  
 #outer --[Hello world]-- outer  

4. Use $(...) for command substitution
 #! /bin/bash  

 echo "outer outer"  
 #output: outer outer  

 echo "outer --$(echo [])-- outer"  
 #output:  
 #outer --[]-- outer  
 #the reason to use double quote "()" is: otherwise () will be taken as  
 #part of command subsitution structure "$(...)"  

 echo "outer --$(echo [$(echo "()")])-- outer"  
 #output:  
 #outer --[()]-- outer  

 echo "outer --$(echo [$(echo "($(echo Hello world))")])-- outer"  
 #output:  
 #outer --[(Hello world)]-- outer  

No comments:

Post a Comment