在shell脚本中使用if结果检查if结果

时间:2017-02-15 07:14:31

标签: bash shell

我正在尝试取消设置有两个' _'我的名字中的字符来自我的数组。但是我得到了权限被拒绝错误。你能帮我解决一下吗?这是我的脚本及其输出:

#!/bin/sh

ALLVERSION=(/dir/test*)
echo "first version:"
for ((i=0; i<${#ALLVERSION[@]}; i++)); do
    if [[ `${ALLVERSION[i]} | grep -o '_' | wc -l` -eq 2 ]]; then
    unset ALLVERSION[i] 
    fi 
done
echo "last version:"
for f in "${ALLVERSION[@]}"; do
   echo "$f"
done 

结果:

first version:
countcharacter.sh: line 6: /dir/test03_01.txt: Permission denied
countcharacter.sh: line 6: /dir/test03_01_01.txt: Permission denied
countcharacter.sh: line 6: /dir/test03_01_04.txt: Permission denied
countcharacter.sh: line 6: /dir/test03_04.txt: Permission denied
countcharacter.sh: line 6: /dir/test03_05_04.txt: Permission denied
countcharacter.sh: line 6: /dir/test04_01_04.txt: Permission denied
countcharacter.sh: line 6: /dir/test05_00.txt: Permission denied
countcharacter.sh: line 6: /dir/test05_01.txt: Permission denied
countcharacter.sh: line 6: /dir/test06_01.txt: Permission denied
last version:
/dir/test03_01.txt
/dir/test03_01_01.txt
/dir/test03_01_04.txt
/dir/test03_04.txt
/dir/test03_05_04.txt
/dir/test04_01_04.txt
/dir/test05_00.txt
/dir/test05_01.txt
/dir/test06_01.txt

3 个答案:

答案 0 :(得分:1)

在将其汇总到echo ${ALLVERSION[i]}之前,您必须grep

if [[ `echo ${ALLVERSION[i]} | grep -o '_' | wc -l` -eq 2 ]]; then

如果没有echo,则会执行${ALLVERSION[i]中存储的文件,并将其输出传递给grep

作为旁注,对于命令替换,您应该使用推荐的$(yourcommand)语法,使其比使用反引号`yourcommand`更具可读性。

答案 1 :(得分:1)

除了这个有用的SLePort's answer之外,您还可以单独使用原生bash工具来满足您的要求,而不是分叉任何第三方工具。

echo "first version:"
for ((i=0; i<${#ALLVERSION[@]}; i++)); do  

    # Strip every character that is not '_', so "${#count}" will be 2 for
    # those lines containing two '_'
    count="${ALLVERSION[i]//[!_]/}"

    if (( "${#count}" == 2 )); then
        unset ALLVERSION[i]
    fi
done

echo "last version:"
for f in "${ALLVERSION[@]}"; do
   echo "$f"
done

答案 2 :(得分:1)

除非您正在处理文件的每一行,否则很少需要>"moveFichierZip.bat" (for /r %a in ("*.zip") do @echo move "%~fa" "x:\somewhere") 。对于单行输入,请使用grep的正则表达式运算符。

bash

或使用扩展模式匹配:

if [[ ${ALLVERSION[i]} =~ /dir/test_[^_]*_[^_]* ]]; then
    unset ALLVERSION[i] 
fi