for循环

form循环脚本 for.sh


#for循环应用


#变量赋值
FILE_TEMP=~/temp/id_dsa.pub
echo 输出变量值:$FILE_TEMP

for k in $( seq 1 10 )

do
    echo 控制台输出:$k
done

输出结果

输出变量值:/home/hadoop/temp/id_dsa.pub
控制台输出:1
控制台输出:2
控制台输出:3
控制台输出:4
控制台输出:5
控制台输出:6
控制台输出:7
控制台输出:8
控制台输出:9
控制台输出:10
  • 遍历目录下的文件或目录

      #!/bin/bash
      DIR="/opt"
      cd $DIR
    
      for k in $(ls $DIR)
      do
        echo $k
      done
      输出结果:
      local
      modules
      resources
    
  • 遍历系统所有进程

      #!/bin/bash
    
      res=`ps -A`
    
      for k in $(ls $res)
      do
        echo $k
      done
      输了的结果:
      System/Library/PrivateFrameworks/AmbientDisplay.framework/Versions/A/XPCServices/com.apple.AmbientDisplayAgent.xpc/Contents/MacOS/com.apple.AmbientDisplayAgent
      /System/Library/PrivateFrameworks/ApplePushService.framework/apsd
      /System/Library/PrivateFrameworks/AskPermission.framework/Versions/A/Resources/askpermissiond
      /System/Library/PrivateFrameworks/AskPermission.framework/Versions/A/Resources/askpermissiond
      /System/Library/PrivateFrameworks/BookKit.framework/Versions/A/XPCServices/com.apple.BKAgentService.xpc/Contents/MacOS/com.apple.BKAgentService
      /System/Library/PrivateFrameworks/CacheDelete.framework/deleted
      /System/Library/PrivateFrameworks/CalendarAgent.framework/Executables/CalendarAgent
      /System/Library/PrivateFrameworks/CalendarAgent.framework/Executables/CalendarAgent
    
  • 查找java程序的所有进程

      #!/bin/bash
    
      res=`ps -A`
    
      processname="java"
      for pid in $(ps aux |grep $processname |grep -v grep|awk '{print $2}')
      do
        echo 进程名称$processname 查找到的进程id:$pid
      done
      结果如下:
      进程名称java 查找到的进程id:1727
      进程名称java 查找到的进程id:1726
      进程名称java 查找到的进程id:1725
    
  • 查找java程序的所有进程,并杀掉

      #!/bin/bash
    
      res=`ps -A`
    
      processname="java"
      for pid in $(ps aux |grep $processname |grep -v grep|awk '{print $2}')
      do
        echo 进程名称$processname 查找到的进程id:$pid
        kill -9   $pid
      done
      结果如下:
      进程名称java 查找到的进程id:1727
      进程名称java 查找到的进程id:1726
      进程名称java 查找到的进程id:1725