moadeep
moadeep

Reputation: 4098

Old csh alias into bash

I'm currently updating some of our scripts from the unreadable world of csh to bash. We have a local alias stored on our system which is used throughout

alias sc 'set \!:2 = `current -\!:1 | cut -c7-`'

This uses a C executable called current which we use to identify the current selected data type. There are 5 data types here image(i), region(r), curve(c), textfile(t) or listfile (l)

The usage of this alias is fairly straightforward sc i A_image

This will find the currently selected image and set the value (which will be an integer) and set the retrieved value to the parameter $A_image which can then be used later in the script.

Similarly sc r Aregion will find the currently selected region and set it to the parameter $Aregion.

I have never really seen the used of !:2 in csh and do not know what it is called. Is there a way I can implement this functionality in bash as it is very useful for our scripts

Upvotes: 1

Views: 108

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

Those appear to be history-like word/argument selectors.

So !:2 is the second argument to the alias and !:1 is the first argument to the alias.

So sc i A_image ends up calling

set A_image = `current -i | cut -c7-`

bash aliases can't take arguments, you need to use functions for that (functions are generally more useful anyway).

The equivalent bash 4.2+ function would be

sc() {
    declare -g "$2=$(current "$1" | cut -c7-)"
}

For bash 3.1+ it would be

sc() {
    printf -v "$2" -- %s "$(current "$1" | cut -c7-)"
}

For older bash or /bin/sh it would be

sc() {
    eval "$2=\$(current \"$1\" | cut -c7-)`"
}

but this version is unsafe in general for untrusted input.

(All functions above untested but should work just fine.)

Upvotes: 1

Related Questions