'How to remove a set of files using a given string containing a wildcarded path in bash/zsh?
Assumption: Let's say I have a wildcarded string variable, which represents a path to a set of files ending with .txt (containing spaces):
a="/hello world/*.txt"
Problem: I want to remove these files in terminal using $rm$:
rm $a
When I execute the above command, I get the following error:
rm: /hello world/*.txt: No such file or directory
Same for below:
rm "$a"
Or even if I escape the spaces, I still get the same error.
Question: How can I remove these paths in bash based on a given wildcard path in a variable format.
More info:
- Output of
$- == 569JNRXZghiklms - OS: Mac OS X 10.15.7
- I'm using zsh
- Output of my bash --version:
❯ bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19) Copyright (C) 2007 Free Software Foundation, Inc.
Solution 1:[1]
This is quite a bit different in zsh from other shells (e.g. bash). In most shells, if you expand a variable without putting double-quotes around it (like rm $a), then the variable's value is subject to both word splitting (i.e. getting broken up into multiple "words") and also wildcard expansion. In zsh, however, neither word splitting nor wildcard expansion is done to variables even if they're not double-quoted (at least by default).
In your case, you need wildcard expansion to be done, but not word splitting (that would break it up into two separate items, "/hello" and "world/*.txt"). In zsh, you can explicitly request that wildcard expansion be done with the ~ prefix:
rm ${~a}
You could also use setopt GLOB_SUBST, which turns wildcard expansion on for all subsequent variable (and command) expansions.
If you were using bash, or some other similar shell, it'd be more complicated, because they don't have natural a way to do wildcard expansion without also doing word splitting. But you can change how the does word splitting, so it doesn't actually do anything:
saveIFS=$IFS
IFS=
rm $a
IFS=$saveIFS
IFS is the list of "whitespace" characters that're treated as word separators; when it's the null string, there are no separators, so no actual splitting happens. But you should be sure to set IFS back to normal afterward, or you can get weird effects.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gordon Davisson |
