Loading...

bash script with ls $variable

Answer #1 100 %

You could use bash's printf command to reformat the string. Furthermore you don't need to quote *:

#!/bin/bash
first="$1"
others=$(printf %q "${first%.001}")
ls $others*

printf %q reformats the string in a format that can be used as shell input (regarding to bash's man page).

edit regarding to a comment:
The above solution does not work with white spaces in file names. For those cases (as some other answers already mentioned) it's better not to use printf but to properly quote all variables:

#!/bin/bash
first="$1"
others="${first%.001}"
ls -- "$others"*

Answer #2 100 %

You should quote the variable, not the wildcard:

ls -- "$others"*

The double dash stops search for options so that this code should work even if others begins with a dash.

Note that ls is more often than not the wrong solution in scripts. Use it only if you really want to print the list, e.g. in long format:

ls -l -- "$others"*

If you want to print only the names, you don't need ls at all:

echo "$others"*

Unfortunately you cannot use -- with echo. If, however, you want an array of the file names, use

filenames=("$others"*)

And should you want to iterate over them, use

for filename in "$others"*
Tags: bash

You’ll also like:


© 2023 CodeForDev.com -