1

Implement a command, that is the content of a variable.

I am trying to create a bash rename program that can rename all the files in a given directory. I have the following program:

for PATHFILE in tracks/*
do
   path="$(dirname "$PATHFILE")"
   file="$(basename "$PATHFILE")"

   program='mv';

   if [[ "$file" =~ ([0-9]*)\s*(.*) ]]
   then

       from=${path}/${file}
       to=${path}/${BASH_REMATCH[1]};

       command_string="$program '$from' '$to'";

       #here the command_string contains the command i want to execute.
       $(command_string);
       #causes error:
       # mv: target ''\''tracks/01'\''' is not a directory.

       break;
    fi

done

If I run the command directly myself then it runs without a problem. I also dont quite get why the system is adding those commas around the string.

If I echo the variable to the screen then i can just copy it, run and it runs without error. but if i try to run it in-code then i keep getting this error.

How do I get this to work?

6
2

First of all, $(command_string) would give you the error "bash: command_string: command not found" as its a command substitution. A command substitution would run the command within the parenthesis and substitute the whole thing with that command's output.

Secondly, even if you had used just $command_string to execute your command, you still add single quotes to the filenames. The filenames don't have single quotes in them.

In general, just avoid putting commands into variables. See "How can we run a command stored in a variable?".

Instead, maybe something like this:

#!/bin/bash

for pathname in tracks/*; do
    if [[ "$pathname" =~ ([0-9]+)[[:blank:]]* ]]; then
        newpathname="${pathname%/*}/${BASH_REMATCH[1]}"
        printf 'Would move "%s" to "%s"\n' "$pathname" "$newpathname"
        # mv -i "$pathname" "$newpathname"
        break
    fi
done

This loop does (I think) what you're trying to do. I've commented out the bit that actually renames the file for safety.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.