繁体   English   中英

通过命令行将参数传递给bash

[英]Giving parameters to bash via command line

我有一个bash脚本,我想在其中运行一堆不同时间的文件。 我不是在创建大量的if语句或创建许多bash脚本,而是在考虑是否有一种方法可以通过命令行接受要在bash中运行的文件。


#!/bin/bash

#generating training data

i_hard=0
i_soft=0
i_neutral=0

for entry in /home/noor/popGen/sweeps/slim_script/final/*
do
    if [[ $entry == *"hard_FIXED"* ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/hard_$i_hard.txt
        i_hard=$((i_hard+1))
    fi

    if [[ $entry == *"soft_FIXED"* ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/soft_$i_soft.txt
        i_soft=$((i_soft+1))
    fi
    if [[ $entry == *"neutral"* ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/neutral_$i_neutral.txt
        i_neutral=$((i_neutral+1))
    fi
done


我想做的是:


#!/bin/bash


i=0

for entry in /home/final/*
do
    if [[ $entry == *parameter* ]]; then
        echo "It's there!"
        /home/stuff/build/./slim $entry > /home/final/parameter_$i.txt
        i=$((i+1))
    fi
done


所以我想“参数”是我想通过命令行提供的参数,可以是hard_FIXED,hard_0等。 我该如何实现?

默认情况下,Shell脚本参数分配为:

$N

此处: N是从0开始的数字。

另外, $0表示脚本文件本身或命令行管理程序。

因此,传递给Shell脚本的参数可用于:

$1$2$3等。

例如:

./script.sh hard_FIXED

hard_FIXED将以$1形式提供。

因此,您可以在脚本中捕获它们并根据需要使用。

可以使用位置参数$ 1找到命令行中bash的第一个参数,因此,如果我的意图正确的话:

#!/bin/bash

#generating training data

i_hard=0
i_soft=0
i_neutral=0

for entry in /home/noor/popGen/sweeps/slim_script/final/*
do
    if [[ $entry == $1 ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/hard_$i_hard.txt
        i_hard=$((i_hard+1))
    fi

    if [[ $entry == $1 ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/soft_$i_soft.txt
        i_soft=$((i_soft+1))
    fi
    if [[ $entry == $1 ]]; then
        echo "It's there!"
        /home/stuff/build/./test $entry > /home/noor/popGen/sweeps/msOut/final/neutral_$i_neutral.txt
        i_neutral=$((i_neutral+1))
    fi
done

查看此处如何使用参数。

#!/bin/bash

# parameter 1 directory
# parameter 2 entry
# check number arguments
if (( $# != 2 )); then
   echo "Usage: $0 directory entry"
   exit 1
fi

# different way of testing, now check directory
test -d "$1" || { echo "$1 is not a directory"; exit 1; }

i=0

for entry in /home/final/*${2}*
do
   # No need for testing [[ $entry == *parameter* ]], this is part of the loop
   echo "${entry}: It's there!"
   /home/stuff/build/slim "${entry}" > /home/final/${2}_$i.txt
   # Alternative for i=$((i+1))
   ((i++))
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM