Vizirship
Vizirship

Reputation: 164

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. 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)

However, when I execute (using ./) it gives me:

No such file or directory] 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?

Upvotes: 3

Views: 9404

Answers (3)

user3075315
user3075315

Reputation: 13

When I had this problem recently, I added a set -x and saw that the directory with wildcards was being single-quoted under the covers. So, instead of

thisDir=$(ls -d /home/test/abc* | head -n1);

It was actually executing as

thisDir=$(ls -d '/home/test/abc*' | head -n1);

Which was looking for a directory literally named abc*.

A co-worker suggested adding set +o noglob ahead of it, which worked. It allows the expansion of wildcard expressions (or technically, disallows the non-expansion of wildcard expressions). But you'll need to determine whether or not you want to set -o noglob afterwards, to keep literal asterisks downstream from your change.

Upvotes: 0

Benjamin Zimmerman
Benjamin Zimmerman

Reputation: 11

I once had a related problem when I tried to cd to my home directory using "~" in a bash script.

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*

Upvotes: -1

norcalli
norcalli

Reputation: 1245

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

Upvotes: 2

Related Questions