如何将命令的输出作为参数列表传递给脚本?

Mil*_*vić 2 ls scripting bash arguments

我想将内容添加到当前目录中每个文件的开头。我需要学习如何一次从当前工作目录中获取所有文件名并将它们作为参数;我不需要通过手动指定每个文件作为脚本的参数来做到这一点。我想将这些新知识用于进一步的脚本。我不需要横向或不同的解决方案。我需要学习如何获取命令 ( ls) 输出并将其作为参数。我尝试过但失败了:

./file-edit.sh $(ls)
./file-edit.sh `ls`
Run Code Online (Sandbox Code Playgroud)

这是我的脚本,它有效:

#!/bin/bash
lineno=2            # Append from line 2 
BAD_ARGS=85         # Error code

string0="###################################################################"
string2="#Description    :"
string3="#Date           :`date +%d-%B-%Y`"
string4="#Author         :Milos Stojanovic"
string5="#Contact:       :https://www.linkedin.com/in/xxx/"
string6="###################################################################"
# Can be any other strings

if [ ! -f $1 ]; then
        echo "Please specify at least 1 filename as an argument!"
        exit $BAD_ARGS
fi

until [ -z  "$1" ]
do
        string1="#Script Name    :$1"
        file=$1;
        sed -i ""$lineno"i $string0\n$string1\n$string2\n$string3\n$string4\n$string5\n$string6" $file
        echo "File "\'$file\'" altered at line number: $lineno"
        shift 1
done

exit 0
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 6

要在脚本中单独处理每个参数,请像这样使用循环:

for pathname do

    # Insert code here that uses "$pathname".
    # You will not need to shift arguments.

done
Run Code Online (Sandbox Code Playgroud)

要使用当前目录中的所有名称调用脚本,请使用

./script.sh ./*
Run Code Online (Sandbox Code Playgroud)

shell 会将./*模式扩展为包含当前目录中所有名称的列表。

与使用ls它不使用的相比,这具有优势,ls因此可以处理包含任何有效字符,甚至空格、制表符和换行符的文件名。

或者,您可以将文件名通配符移动到脚本本身(以避免必须在命令行上为脚本提供任何参数)

for pathname in ./*; do
    # Insert code here that uses "$pathname".
done
Run Code Online (Sandbox Code Playgroud)

如果您的脚本需要区分引用常规文件的名称和引用非常规文件(例如目录)的名称,请-f在循环中使用测试:

# skip non-regular files
[ ! -f "$pathname" ] && continue
Run Code Online (Sandbox Code Playgroud)

这仍然会允许通过符号链接到常规文件。要跳过这些,请将测试更改为

if [ ! -f "$pathname" ] || [ -L "$pathname" ]; then
    # Skip non-regular files and symbolic links.
    continue
fi
Run Code Online (Sandbox Code Playgroud)

其他的建议:

您可以通过在字符串中包含换行符来将多行字符串分配给变量:

boilerplate='Hello and welcome!
This is my program.
Enjoy'
Run Code Online (Sandbox Code Playgroud)

要在文本文档中的第二行之后插入文本,请使用sed-i此处用于就地编辑):

printf '%s\n' "$boilerplate" | sed -i '2r /dev/stdin' somefile
Run Code Online (Sandbox Code Playgroud)

或者,使用此处的文档,

sed -i '2r /dev/stdin' somefile <<END_BOILERPLATE
Hello and welcome!
This is my program.
Enjoy
END_BOILERPLATE
Run Code Online (Sandbox Code Playgroud)