在 Shell 个脚本中分配参数

Assigning Arguments in Shell Scripts

所以我是 shell 脚本的新手,目前我有一个 sheLL 我打电话给 运行 我的其他人它看起来像这样

  # RC Script Call 
if [ "" = "runrc" ]
then
    echo "RC folder Setup is running"
    echo ""
    sh ./RCFolderSetup.sh
fi

if [ "" = "runrc" ]
then
    echo "RC folder Setup is running"
    echo ""
    sh ./RCFolderSetup.sh
fi

if [ "" = "runrc" ]
then
    echo "RC folder Setup is running"
    echo ""
    sh ./RCFolderSetup.sh
fi

# Trunk Script Call 
if [ "" = "runtrunk" ]
then
    echo "Trunk folder Setup is running"
    echo ""
    sh ./TrunkFolderSetup.sh
fi

if [ "" = "runtrunk" ]
then
    echo "Trunk folder Setup is running"
    echo ""
    sh ./TrunkFolderSetup.sh
fi

if [ "" = "runtrunk" ]
then
    echo "Trunk folder Setup is running"
    echo ""
    sh ./TrunkFolderSetup.sh
fi

# Testing Script Call 
if [ "" = "runtest" ]
then
    echo "Test folder Setup/Push the files is running"
    echo ""
    sh ./TestingScript.sh
fi

if [ "" = "runtest" ]
then
    echo "Test folder Setup/Push the files is running"
    echo ""
    sh ./TestingScript.sh
fi

if [ "" = "runtest" ]
then
    echo "Test folder Setup/Push the files is running"
    echo ""
    sh ./TestingScript.sh
fi

如您所见,我必须为所有内容分配一个以上的值,我的问题是,他们是否是一种更简单的方法来编写此脚本,但仍然让它做同样的事情

我认为一个理智的替代品是

#!/bin/sh

# while the number of arguments is not zero    
while [ "$#" -gt 0 ]; do

    # do the stuff for the first argument
    case "" in
        runrc)
            echo "RC folder Setup is running"
            echo ""
            sh ./RCFolderSetup.sh
            ;;
        runtrunk)
            echo "Trunk folder Setup is running"
            echo ""
            sh ./TrunkFolderSetup.sh
            ;;
        runtest)
            echo "Test folder Setup/Push the files is running"
            echo ""
            sh ./TestingScript.sh
            ;;
    esac

    # and shift the arguments back one so that  becomes ,  becomes ,
    # and so forth
    shift
done

如果执行顺序很重要(即使参数混乱也应该固定),这种方法可以修改为

#!/bin/sh

while [ "$#" -gt 0 ]; do
    case "" in
        runrc)
            do_runrc=yes
            ;;
        runtrunk)
            do_runtrunk=yes
            ;;
        runtest)
            do_runtest=yes
            ;;
    esac

    shift
done

if [ "$do_runrc" = yes ]; then
    echo "RC folder Setup is running"
    echo ""
    sh ./RCFolderSetup.sh
fi

if [ "$do_runtrunk" = yes ]; then
    echo "Trunk folder Setup is running"
    echo ""
    sh ./TrunkFolderSetup.sh

fi

if [ "$do_runtest" = yes ]; then
    echo "Test folder Setup/Push the files is running"
    echo ""
    sh ./TestingScript.sh
fi

像这样为 if 块创建一个函数:

checkArg() {
    if [ "" = "" ]; then
      echo ""
      echo 
      sh ""
   fi
}

然后将其命名为:

checkArg "" "runtrunk" "Trunk folder Setup is running" "./TrunkFolderSetup.sh"

checkArg "" "runtrunk" "Trunk folder Setup is running" "./TrunkFolderSetup.sh"

checkArg "" "runrc" "RC folder Setup is running" "./RCFolderSetup.sh"

## ...
## ...