简体   繁体   English

Bash 带有通配符的脚本

[英]Bash script with wildcards

here's an example of my script:这是我的脚本的一个例子:

#!/bin/bash
cd /upper/folder.test*/subfolder
ls

The folder.test folder s actually named something like "folder.test13kwekrjk1234jk3", and it's completely random, so I want to use a wild card. folder.test 文件夹实际上命名为“folder.test13kwekrjk1234jk3”,它是完全随机的,所以我想使用通配符。 The "Upper" folder is in root, where I want it and the CD command works outside the script (and I'm executing it in the root directory, just like the script) “上”文件夹位于根目录中,我想要它,并且 CD 命令在脚本之外工作(我在根目录中执行它,就像脚本一样)

However, when I execute (using./) it gives me:但是,当我执行(使用./)时,它给了我:

"- No such file or directory] cd:/upper/folder.test*/subfolder" "- 没有这样的文件或目录] cd:/upper/folder.test*/subfolder"

What gives?是什么赋予了? It works outside of the script but it won't work inside the script?它在脚本之外工作,但在脚本内部不起作用? Should I be doing this a different way inside the script?我应该在脚本中以不同的方式执行此操作吗?

You could do this instead because wildcards are literally wildcards, their behavior is hard to predict and less reliable.您可以改为这样做,因为通配符实际上就是通配符,它们的行为难以预测且可靠性较低。

FOLDER=$(ls -1 /upper/folder.test*/subfolder | head -n1);
cd "$FOLDER"
ls

I once had a related problem when I tried to cd to my home directory using "~" in a bash script.当我尝试在 bash 脚本中使用“~” cd 到我的主目录时,我曾经遇到过一个相关的问题。

This code worked in the terminal, but not in my script:此代码在终端中有效,但在我的脚本中无效:

cd ~/Documents/important_folder* 

However, the below code worked fine in the script:但是,以下代码在脚本中运行良好:

cd /home/my_username/Documents/important_folder*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM