You are not logged in.

#1 2019-06-04 00:47:18

mountaineerbr
Banned
Registered: 2018-12-08
Posts: 48

[ Solved ] How to expand all Bash Variables with a certain prefix ..

Hello all.

I am trying to make a backup script.

I am assigning folder paths to variables in a script, and I'd like
all variables would be expanded to their values.

Maybe an example will help to explain

DIR1=/home/user/Docs
DIR2=/home/user/Vids
DIR3=/home/user/Music

tar --create --xz --file=/home/Backup.tar.xz "${!DIR@}"

According to the manual:
"    ${!prefix@}
Expands to the names of variables whose names begin with prefix..."

So only expanding to the names, not the values of my variables will not help.

Last edited by mountaineerbr (2019-06-04 01:59:24)

Offline

#2 2019-06-04 01:08:47

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: [ Solved ] How to expand all Bash Variables with a certain prefix ..

┌─[Veles ~]
└─╼ array=(/home/user/data /home/user/music /home/user/pr0n)
┌─[Veles ~]
└─╼ printf "%s\n" "${array[@]}"
/home/user/data
/home/user/music
/home/user/pr0n

Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#3 2019-06-04 01:21:12

mountaineerbr
Banned
Registered: 2018-12-08
Posts: 48

Re: [ Solved ] How to expand all Bash Variables with a certain prefix ..

Thank you, anarchist...

I will use arrays.

Offline

#4 2019-06-04 01:26:53

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,449
Website

Re: [ Solved ] How to expand all Bash Variables with a certain prefix ..

You ask about 'sh' but reference part of the BASH manual.  If you are using BASH, the above mentioned array would likely be best, but not really necessary, just define a variable as a list:

DIRS="
        /home/user/Docs
        /home/user/Vids
        /home/user/Music
        "
tar --create --xz --file=/home/Backup.tar.xz $DIRS

Also note that in BASH, the DIR prefix will likely also match other things in the environment that you would not intend (e.g., DIRSTACK).

If you are in fact using 'sh' and not BASH, then you'd have to use a list, or the argv array:

set -- \
   /home/user/Docs \
   /home/user/Vids \
   /home/user/Music

tar --create --xz --file=/home/Backup.tar.xz "$@"

"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#5 2019-06-04 01:58:38

mountaineerbr
Banned
Registered: 2018-12-08
Posts: 48

Re: [ Solved ] How to expand all Bash Variables with a certain prefix ..

Hey Trilby..

Thanks for pointing to the fact it is possible to define a variable as a list..
It never crossed my mind that that would actually work!

About the question title, SH because I could not type all the question length
so I had to try and abbreviate something.. But I will change it again to state
it is a  bash question, but the question title will still be incomplete.

Learning bash  was indeed very productive for me today..

Offline

Board footer

Powered by FluxBB