0

I can't use environment variables with chmod command. Is there any workaround to run this?

The way I'm trying to run in a sh file

export PEM_FILE="~/.ssh/xxx.pem"
chmod 400 $PEM_FILE

Output

chmod: ~/.ssh/xxx.pem: No such file or directory

However, it work perfectly fine without the variable like this: chmod 400 ~/.ssh/xxx.pem

P.S: I am on macOS. Kindly let me know if this works fine in windows or linux.

Thanks!

2 Answers2

0

Unfortunately, special characters like ~ do not work in strings. Instead, use a variable like $HOME to point to the home directory, or remove the quotes. (not recommended because it breaks compatibility with some shells)

So you would do something like: export PEM_FILE="$HOME/.ssh/xxx.pem" or export PEM_FILE=~/.ssh/xxx.pem.

gorgo
  • 116
  • 3
  • why are you hard-coding the path? On my system, ~user is /home2/user; It could also be something else, not including user in any way or form. That also prevents the user from overriding it via HOME=/some/path /path/to/script. –  Nov 12 '21 at 00:36
  • It's not that they "don't work in variables", it's rather that they're not expanded within quotes, so the expanded value isn't even stored in the variable. chmod 400 "~/.ssh/xxx.pem" would have the same problem. – DonHolgo Nov 12 '21 at 10:10
0

The issue is that ~ is wildcard, and bash usually expands all wildcards and perform variable expansion BEFORE executing command. But in your case, you are using quotas and this prevent bash from wildcard resolution, so

export PEM_FILE="~/.ssh/xxx.pem"

PEM_FILE will contains not the path to the file but the string. And chmod command will receive this string as an argument, again without performing resolving wildcard.

So just remove quota

export PEM_FILE=~/.ssh/xxx.pem

or use full path

export PEM_FILE="/home/username/.ssh/xxx.pem"

Both will works.

Saboteur
  • 186
  • 5