Bash Script: How to enable for the wildcard in variable to expand in for flow control?

I have practiced for flow control, referencing a sample script like;

if [ $(id -u) = "0" ]; then dir_list="/home/*" else dir_list=$HOME fi for home_dir in $dir_list; do

The above is partly quoted lines from "Flow Control - Part 3"

Then,to check how the wildcard in a variable behaves in for flow control, I tried the lines below;

#!/bin/bash
binlist="~/bin/*"
for i in $binlist; do
echo $i
done

I wanted the wildcard to expand and all files in ~/bin/ to be displayed as outputs, but it did not happen. The output is just ~/bin/*.

If I do not use the variable, and directly assign ~/bin/* into the list of for, what I expect happens, all files in ~/bin/ are displayed.

QUESTION=====

How can I enable for a wildcard in variable to expand?

Or am I misunderstanding what the sample code of the reference site intends?

=============

Thank you for your reading my question!

8

1 Answer

You can use the bash variable for your home directory instead of ~.

The bash variable for your home directory is $HOME so your script should look like this:

#!/bin/bash
binlist="$HOME/bin/*"
for i in $binlist; do
echo $i
done

Alternatively, you could use /home/$USER instead of $HOME like this:

#!/bin/bash
binlist="/home/$USER/bin/*"
for i in $binlist; do
echo $i
done

You can view each one of these variables by running the following commands:

echo $HOME
echo $USER

These are listed under "Shell Variables" on the bash manpage.


Also, as mentioned by @John1024, the tilde will not expand to $HOME if it is placed within quotes so your third option would be to use the following:

#!/bin/bash
binlist=~/"bin/*"
for i in $binlist; do
echo $i
done

and as mentioned by @bac0n the quotation marks are not necessary here so you can also use the following:

#!/bin/bash
binlist=~/bin/*
for i in $binlist; do
echo $i
done
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like