1

Is it possible to create an alias which contains a variable in its name (i.e. without space)? I would like to set conversion shortcuts like hexa to binary:

For instance, when I enter:

0xff

I would like to display the following:

11111111

The idea would be something like (this example is obviously not working):

alias 0x$1='echo "obase=2; ibase=16; $1" | bc'

2 Answers 2

2

bash aliases does not take variables as input(s). You can use a function instead:

$ hex_to_bin () { echo "obase=2; ibase=16; $1" | bc ;}

$ hex_to_bin 6A
1101010
Sign up to request clarification or add additional context in comments.

Comments

1

No, in bash, aliases work on individual words. So, unless you want to do:

alias 0x00='echo 00000000'
alias 0x01='echo 00000001'

then you're not going to get it working easily. It can be done (for a limited range) using that method by creating a script to source on the fly but it will result in a lot of aliases:

( for i in {0..255} ; do printf "alias 0x%02x='echo %d'\n" $i $i ; done ) >xyzzy_$$.sh
source xyzzy_$$.sh
rm xyzzy_$$.sh

Instead, I'd just opt for an function x where you could do:

pax> x ff
11111111

There are no more keystrokes than you would need for 0xff and you don't have to worry about trying to coerce bash into doing something it's not really built to do.

Such a function can be created with:

pax> x() {
...>    val=$(tr '[a-z]' '[A-Z]' <<< $1)
...>    BC_LINE_LENGTH=0 bc <<< "ibase=16;obase=2;$val"
...> }

and used as follows:

pax> x ff
11111111

pax> x 42
1000010

pax> x cB
11001011

pax> x 457365384563453653276537456354635635326535635345
10001010111001101100101001110000100010101100011010001010011011001010011001001110110010100110111010001010110001101010100011000110101011000110101001100100110010100110101011000110101001101000101

Note the use of tr to coerce alphas into uppercase values. Without that, you're likely to run into problems with bc recognising them as valid hex digits.

Also note the setting of BC_LINE_LENGTH to prevent bc from auto-wrapping very large numbers, such as that last one where you would otherwise see:

pax> y 457365384563453653276537456354635635326535635345
10001010111001101100101001110000100010101100011010001010011011001010\
01100100111011001010011011101000101011000110101010001100011010101100\
0110101001100100110010100110101011000110101001101000101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.