脚本失败,但从脚本复制和粘贴有效

脚本失败,但从脚本复制和粘贴有效

我编写了一个脚本来检查计算机的处理器数量,然后根据该脚本更改另一个脚本中处理器编号的所有引用。我首先通过将其复制并粘贴到终端中进行测试。我可以将整个脚本复制到命令行中并且它可以工作。但是当我将它作为脚本运行时,它一半失败了。

这是脚本(我知道它很笨重,而且肯定有一种更简单的运行方法,但这很容易写出我的想法,如果你有这个脚本的更好版本和修复程序,那么那就是惊人的!)

#!/bin/sh
# This part works both in the script and when pasting into the terminal.
echo | nproc >  ~/tmp/ProcessorNumber.txt
echo | perl -pi -e 's/processors=1/processors=8/g' ~/Scripts/test.sh
echo | perl -pi -e 's/processors=2/processors=8/g' ~/Scripts/test.sh
echo | perl -pi -e 's/processors=3/processors=8/g' ~/Scripts/test.sh
echo | perl -pi -e 's/processors=4/processors=8/g' ~/Scripts/test.sh
echo | perl -pi -e 's/processors=5/processors=8/g' ~/Scripts/test.sh
echo | perl -pi -e 's/processors=6/processors=8/g' ~/Scripts/test.sh
echo | perl -pi -e 's/processors=7/processors=8/g' ~/Scripts/test.sh

# This part of the script isn't working when run as script
# but is working when pasted into the command line.
if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 1 ))
    then
        echo | perl -pi -e 's/processors=8/processors=1/g' ~/Scripts/test.sh
    else
        echo | ""
fi       

if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 2 ))
    then
        echo | perl -pi -e 's/processors=8/processors=2/g' ~/Scripts/test.sh
    else
        echo | ""
fi 

if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 3 ))
    then
        echo | perl -pi -e 's/processors=8/processors=3/g' ~/Scripts/test.sh
    else
        echo | ""
fi 

if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 4 ))
    then
        echo | perl -pi -e 's/processors=8/processors=4/g' ~/Scripts/test.sh
    else
        echo | ""
fi 

if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 5 ))
    then
        echo | perl -pi -e 's/processors=8/processors=5/g' ~/Scripts/test.sh
    else
        echo | ""
fi 

if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 6 ))
    then
        echo | perl -pi -e 's/processors=8/processors=6/g' ~/Scripts/test.sh
    else
        echo | ""
fi 

if (( $(head -n1 ~/tmp/ProcessorNumber.txt) == 7 ))
    then
        echo | perl -pi -e 's/processors=8/processors=7/g' ~/Scripts/test.sh
    else
        echo | ""
fi

答案1

试试这个脚本:

#!/bin/sh
sed -i -e "s/processors=[0-9]\+/processors=$(nproc)/g" ~/Scripts/test.sh

sed是一个流编辑器。-iswitch 告诉它进行所有更改,-e尽管是可选的,但告诉它以下参数是一个sed脚本

相关内容