Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variable with leading digit in bash

I need to set an environment variable called "64bit" (i.e. with a leading digit) in bash. However, bash variable names disallow a variable with a leading digit. I know a way to set it when invoking bash:

env 64bit=1 /usr/bin/bash

However, I'm looking for a way to change it in the currently running shell i.e. not by starting a new shell. I also know that csh allows variables to start with a digit, but I need to use bash.

Is there any way to achieve this?

like image 227
Haitham Gad Avatar asked Mar 19 '13 19:03

Haitham Gad


2 Answers

You can also bypass the bash interpreter and define the variable directly with the bash internal functions:

$ gdb --batch-silent -ex "attach $$"                              \
    -ex 'set bind_variable("64bit", "1", 0)'                      \
    -ex 'set *(int*)(find_variable("64bit")+sizeof(char*)*5) = 1' \
    -ex 'set array_needs_making = 1'

$ env | grep 64
64bit=1
like image 74
BeniBela Avatar answered Nov 03 '22 00:11

BeniBela


As people point out, Bash does not allow variables starting with digits. It does however pass on unrecognized environment string to external programs, which is why the variable shows up in env but not in set.

As a workaround, you can work with a valid name like _64bit and then automatically inject your invalid variable name into commands you run:

#!/bin/bash    
# Setup for injection hack
original=$PATH
PATH="/"
command_not_found_handle() {
  PATH="$original" env "64bit=$_64bit" "$@"
}

# Your script and logic
_64bit="some dynamic value"

# This verifies that '64bit' is automatically set
env | grep ^64bit

Note that this particular method only works if you invoke through $PATH, not if you use relative or absolute path names.

If you do invoke by pathname, consider modifying PATH and invoking by name instead.

like image 42
that other guy Avatar answered Nov 03 '22 02:11

that other guy