简体   繁体   English

使用名称中没有空格的变量创建bash别名

[英]Create a bash alias with a variable in the name without space

Is it possible to create an alias which contains a variable in its name (ie without space )? 是否可以创建一个名称中包含变量的别名(即没有空格 )? I would like to set conversion shortcuts like hexa to binary: 我想将转换快捷方式(如hexa)设置为二进制:

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'

bash aliases does not take variables as input(s). bash别名不将变量作为输入。 You can use a function instead: 您可以改为使用函数:

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

$ hex_to_bin 6A
1101010

No, in bash , aliases work on individual words. 不,在bash ,别名可以处理单个单词。 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: 相反,我只是选择一个函数x ,你可以做:

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. 没有更多的按键比你需要为0xff ,你不担心试图强迫bash到做一些它不能真正建立这样做。

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. 请注意使用tr将alpha强制转换为大写值。 Without that, you're likely to run into problems with bc recognising them as valid hex digits. 没有它,你可能会遇到bc将它们识别为有效十六进制数字的问题。

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: 另请注意BC_LINE_LENGTH的设置,以防止bc自动换行非常大的数字,例如你可能会看到的最后一个数字:

pax> y 457365384563453653276537456354635635326535635345
10001010111001101100101001110000100010101100011010001010011011001010\
01100100111011001010011011101000101011000110101010001100011010101100\
0110101001100100110010100110101011000110101001101000101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM