shell中子shell的妙用

shell脚本子shell的妙用

目录结构

├── a
├── b
├── c
├── d
└── test.sh

现有这样一段脚本(此处代码加上行号是为了方便说明)

 1 #!/bin/bash
  2 
  3 set -e
  4 
  5 pwd=`pwd`
  6 
  7 for file in  `ls $pwd`
  8 do
  9    if [ -d $file ]
 10    then
 11        cd $pwd/$file
 12        echo $file
 13    fi
 14 done

执行该脚本后,得出的结果是

a

这里很有意思的地方是,for循环仅仅执行了一次就退出了

内建的cd 命令切换了目录以后 居然会导致当前的循环中断

为了避免这种情况的发生,我们可以借鉴一下子shell的概念 把cd 命令当成子shell作为独立的进程来运行 这样就不会对当前的脚本产生影响了

# 子shell的格式是用括号把一系列的命令包裹起来
(
    command1
    command2
    command3
)

因此经过一番修改,我得到了下面的脚本(在11和14行代码处加上了括号)

  1 #!/bin/bash
  2 
  3 set -e
  4 
  5 pwd=`pwd`
  6 
  7 for file in  `ls $pwd`
  8 do
  9    if [ -d $file ]
 10    then
 11     (
 12        cd $pwd/$file
 13        echo $file
 14     )
 15    fi
 16 done

这样就能得出正常的结果了

a
b
c
d

《shell中子shell的妙用》上有78条评论

  1. Pingback: viagra
  2. Pingback: Masum
  3. Pingback: ivermectin for humans
  4. Pingback: stromectol for sale
  5. Pingback: how to get ivermectin
  6. Pingback: ivermectin 12 mg
  7. Pingback: ivermectin malaria
  8. Pingback: cheap viagra pills uk
  9. Pingback: tadalafil mexico
  10. Pingback: tadalafil sale
  11. Pingback: viagra tablets
  12. Pingback: furosemide 40
  13. Pingback: lasix price
  14. Pingback: buy tadalafil powder
  15. Pingback: cialis for men
  16. Pingback: cialis online
  17. Pingback: tadalafil liquid
  18. Pingback: molnupirawir
  19. Pingback: generique cialis
  20. Pingback: revatio sildenafil
  21. Pingback: cialis professional
  22. Pingback: viagra free delivery
  23. Pingback: buy levitra online
  24. Pingback: ceallias
  25. Pingback: borgata free casino
  26. Pingback: cialis price walmart
  27. Pingback: ivermectin nahdi
  28. Pingback: ivermectin 1
  29. Pingback: real casino online
  30. Pingback: tadalafil femme
  31. Pingback: cialis best price
  32. Pingback: viagra pfizer
  33. Pingback: tadalafil otc
  34. Pingback: stromectol sale
  35. Pingback: ivermectina oral
  36. Pingback: ivermectin 5 mg price
  37. Pingback: get stromectol
  38. Pingback: lasix 500 mg tab
  39. Pingback: lasix drug
  40. Pingback: ivermectine
  41. Pingback: ivermectin for pigs
  42. Pingback: what is ivermectin
  43. Pingback: buy ivermectin cream

发表评论