Saturday, November 13, 2021

[SOLVED] Prevent variable expansion in the parameter of a function to be expanded in a for loop

Issue

I am building a generic function exec_all_dirs in bashrc that would run a command in multiple directories.

function exec_all_dirs() {
  curdir=$PWD
  dirs=(
    ~/dir1
    ~/dir2
    ~/dir3
  )
  for dir in ${dirs[@]};
  do
    echo "---------- $dir ---------"
    "$@"                                                          # run the command here.
  done
  cd $curdir
}

function all_func() {
  exec_all_dirs 'cd $dir && another_func_defined_in_bashrc'       # how to pass $dir
}
function all_du() {
  exec_all_dirs 'du -sh $dir'
}

How can I pass $dir as argument to exec_all_dirs so it gets expanded in the for loop?


Solution

Try like this:

exec_all_dirs(){
    local curdir=$PDW
    local cmd dir
    local dirs=(
        ~/dir1
        ~/dir2
        ~/dir3
    )
    for dir in ${dirs[@]}; do
        echo      "---------- $dir ---------"
        printf -v   cmd "$1" "$dir"
        bash   -c "$cmd"
    done
    cd $curdir
}

all_fu(){ exec_all_dirs 'cd %s && another_func_defined_in_bashrc'; }
all_du(){ exec_all_dirs 'du -sh %s'; }


Answered By - Ivan