bash 目录路径作为bash中的命令行参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20151648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:44:01  来源:igfitidea点击:

directory path as command line argument in bash

linuxbashdirectorycommand-line-arguments

提问by user227666

The following bash script finds a .txtfile from the given directory path, then changes one word (change mountain to sea) from the .txtfile

下面的 bash 脚本.txt从给定的目录路径中找到一个文件,然后从.txt文件中更改一个单词(将山更改为海)

#!/bin/bash
FILE=`find /home/abc/Documents/2011.11.* -type f -name "abc.txt"`
sed -e 's/mountain/sea/g' $FILE 

The output I am getting is ok in this case. My problem is if I want to give the directory path as command line argument then it is not working. Suppose, I modify my bash script to:

在这种情况下,我得到的输出没问题。我的问题是,如果我想将目录路径作为命令行参数提供,则它不起作用。假设,我将 bash 脚本修改为:

#!/bin/bash
FILE=`find  -type f -name "abc.txt"`
sed -e 's/mountain/sea/g' $FILE 

and invoke it like:

并像这样调用它:

./test.sh /home/abc/Documents/2011.11.*

Error is:

错误是:

./test.sh: line 2: /home/abc/Documents/2011.11.10/abc.txt: Permission denied

Can anybody suggest how to access directory path as command line argument?

有人可以建议如何访问目录路径作为命令行参数吗?

回答by Barmar

Your first line should be:

你的第一行应该是:

FILE=`find "$@" -type f -name "abc.txt"`

The wildcard will be expanded before calling the script, so you need to use "$@"to get all the directories that it expands to and pass these as the arguments to find.

通配符将在调用脚本之前扩展,因此您需要使用它"$@"来获取它扩展到的所有目录并将这些作为参数传递给find.

回答by anubhava

You don't need to pass .*to your script.

您不需要传递.*给您的脚本。

Have your script like this:

让你的脚本是这样的:

#!/bin/bash

# some sanity checks here
path=""

find "$path".* -type f -name "abc.txt" -exec sed -i.bak 's/mountain/sea/g' '{}' \;

And run it like:

并像这样运行它:

./test.sh "/home/abc/Documents/2011.11"

PS:See how sed can be invoked directly from find itself using -execoption.

PS:查看如何使用-exec选项直接从 find 自身调用 sed 。