Search code examples
bashparametersediting

adding to and changing a parameter in bash


Is there a way to take a parameter regardless of what it is and change it to a more specific output.

I'm trying to find a way that I can change M26 (or M27, M28, L26, L27....) to M0000026.00 so later on in the script I can call on the new form of the parameter

I know i could do something like:

./test.sh M26

if [ "$1" = M26 ]

   then

   set -- "M0000026.00" "${@:1}"

fi

some function to call $1 in file string /..../.../.../$1/.../..

but I'm looking more for a generic way so I don't have to input all the possible if statements for every 3 character parameter I have


Solution

  • If your version of bash supports associative arrays, you can do something like this:

    # Declare an associative array to contain your argument mappings
    declare -A map=( [M26]="M0000026.00" [M27]="whatever" ["param with spaces"]="foo" )
    
    # Declare a regular array to hold your remapped args
    args=()
    
    # Loop through the shell parameters and remap them into args()
    while (( $# )); do
       # If "$1" exists as a key in map, then use the mapped value.
       # Otherwise, just use "$1"
       args+=( "${map["$1"]-$1}" )
       shift
    done
    
    # At this point, you can either just use the args array directly and ignore
    # $1, $2, etc. 
    # Or you can use set to reassign $1, $2, etc from args, like so:
    set -- "${args[@]}"
    

    Also, you don't have to declare map on a single line as I did. For maintainability (especially if you have lots of mappings), you can do it like this:

    declare -A map=()
    map["M26"]="M0000026.00"
    map["M27"]="whatever"
    ...
    map["Z99"]="foo bar"