美文网首页
shell入门21-移动位置参数shift

shell入门21-移动位置参数shift

作者: 万州客 | 来源:发表于2023-01-04 21:08 被阅读0次

    shift,我之前真的没用过呢~

    一,介绍

    image.png
    image.png

    二,练习

    [root@127 shell_demo]# vim parameter.sh
    [root@127 shell_demo]# bash parameter.sh 
    arg1=, arg2=, arg3=, arg4=, arg5=, arg6=, count=0
    arg1=, arg2=, arg3=, arg4=, arg5=, arg6=, count=0
    arg1=, arg2=, arg3=, arg4=, arg5=, arg6=, count=0
    arg1=, arg2=, arg3=, arg4=, arg5=, arg6=, count=0
    [root@127 shell_demo]# bash parameter.sh a b c 1 2 3
    arg1=a, arg2=b, arg3=c, arg4=1, arg5=2, arg6=3, count=6
    arg1=b, arg2=c, arg3=1, arg4=2, arg5=3, arg6=, count=5
    arg1=1, arg2=2, arg3=3, arg4=, arg5=, arg6=, count=3
    arg1=2, arg2=3, arg3=, arg4=, arg5=, arg6=, count=2
    [root@127 shell_demo]# cat parameter.sh 
    #!/bin/bash
    # 功能描述:演示shift命令的作用,左移位置参数
    
    echo "arg1=$1, arg2=$2, arg3=$3, arg4=$4, arg5=$5, arg6=$6, count=$#"
    shift
    echo "arg1=$1, arg2=$2, arg3=$3, arg4=$4, arg5=$5, arg6=$6, count=$#"
    shift 2
    echo "arg1=$1, arg2=$2, arg3=$3, arg4=$4, arg5=$5, arg6=$6, count=$#"
    shift 1
    echo "arg1=$1, arg2=$2, arg3=$3, arg4=$4, arg5=$5, arg6=$6, count=$#"
    [root@127 shell_demo]# vim empty.sh
    [root@127 shell_demo]# touch a.txt b.txt
    [root@127 shell_demo]# echo "111" > 1.txt
    [root@127 shell_demo]# echo "222" > 2.txt
    [root@127 shell_demo]# mkdir test
    [root@127 shell_demo]# bash empty.sh a.txt 1.txt b.txt 2.txt test/
    a.txt 为空文件,正在删除该文件. 
    1.txt为非空文件。
    b.txt 为空文件,正在删除该文件. 
    2.txt为非空文件。
    test/为文件夹。
    [root@127 shell_demo]# cat empty.sh 
    #!/bin/bash
    # 功能描述:读取位置参数,测试是否空文件并删除空文件
    
    if [ $# -eq 0 ]; then
      echo "用法:$0 文件名..."
      exit 1
    fi
    
    # 测试位置变量个数,个数为0时循环结束
    while (($#)); do
      if [ ! -s $1 ]; then
        echo -e "\033[31m$1 为空文件,正在删除该文件. \033[0m"
        rm -rf $1
      else
        [ -f $1 ] && echo -e "\033[32m$1为非空文件。\033[0m"
        [ -d $1 ] && echo -e "\033[32m$1为文件夹。\033[0m"
      fi
      shift
    done
    

    相关文章

      网友评论

          本文标题:shell入门21-移动位置参数shift

          本文链接:https://www.haomeiwen.com/subject/ghkccdtx.html