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
  • 1
    See Simple variable assignment: Tilde does not expand in quotes Commented Nov 11, 2021 at 23:49
  • tl;dr; just use export PEM_FILE=~/.ssh/xxx.pem (or PEM=$HOME/.ssh/xxx.pem; export PEM, which will work in all bourne-like shells). No, the quotes aren't needed with export PEM=.... But they are needed with chmod 400 "$PEM_FILE". Commented Nov 12, 2021 at 0:29

2 Answers 2

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.

2
  • 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. Commented Nov 12, 2021 at 0: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. Commented Nov 12, 2021 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.