Написание сценария Unix (bash), который создает каталог в месте, указанном в командной строке

2370
David

В настоящее время у меня есть сценарий Unix (написанный на bash), который выполняет несколько команд для изменения группы файлов, которые я указываю с помощью flist, содержащего их пути. Основная идея сценария - создать каталог, поместить файлы из flist в этот каталог, а затем выполнить последующие процессы, некоторые из которых создают больше каталогов.

Проблема, с которой я столкнулся, заключается в том, что я должен указать точный путь к файлу, в котором я хочу, чтобы каталоги находились внутри самого скрипта. Итак, мой вопрос: есть ли способ написать сценарий так, чтобы я мог ввести команду, а затем путь к папке назначения, где я хотел бы, чтобы сценарий выполнялся в командной строке и имел начальный и все последующие каталоги, созданные сценарием в начальном каталоге без необходимости указывать какой-либо из их путей (например, 'command / destination / path / for / script /')?

Извинения, если это немного затянуто. Я довольно новичок в Unix и у меня очень мало опыта (и, следовательно, я не смог придумать лучшую формулировку). Любая помощь приветствуется!

0

2 ответа на вопрос

3
terdon

If I understand you correctly, you are asking how to pass values to a bash script. This is very easy, for example:

#!/usr/bin/env bash directory=$1; echo "Directory is $directory" 

$1 is the first command line argument of a bash script. $2 is the second etc etc. So, you could run the script above like so:

./foo.sh /path/to/bar Directory is /path/to/bar 

If you want the command to be a variable as well, you could do something like this:

 #!/usr/bin/env bash command=$1; directory=$2 $command $directory 

So, to run ls /etc, you would run the script above like this:

./foo.sh ls /etc 
+1 за представление портативного решения (используя env). Hennes 11 лет назад 0
Это именно то, что я искал. Спасибо!! David 11 лет назад 0
0
Ramillete

I imagine that you have files in a place (/path/to/originals) and want to copy them to a target location (/path/to/destination) and modify them afterwards. Your current script looks like:

mkdir /path/to/destination cp /originals/this-file /path/to/destination cp /originals/this-other-file /path/to/destination modify-somehow /path/to/destination/this-file modify-somehow /path/to/destination/this-other-file 

but you don't like to have to hardcode /path/to/destination everywhere. So you can ask to use "the value of the first positional parameter" instead of hardcoding /path/to/destination. As others mentioned, the value of the first positional parameter is $1.

So your script should be:

mkdir $1 cp /originals/this-file $1 cp /originals/this-other-file $1 modify-somehow $1/this-file modify-somehow $1/this-other-file 

And you should invoke this by adding the destination path as an argument:

my-script /path/to/destination 

I tried to keep the script simple, but you could improve it, like using a single cp command to copy several files. You can also use a variable for your /originals path (but instead of an argument, this one sounds like a constant declaration at the beginning of your script)

Lastly, consider that if your filenames have spaces, you'll need to surround your $1 in double quotes.

Похожие вопросы