coffeecola
coffeecola

Reputation: 100

bash variable filename with underscore unrecognized?

I am writing a script that will symlink all of my dotfiles related to bash into the home directory. I want the script to check if the filenames already exists, so that I I can rename/move them.

For some reason can't get my if test-command to recognize filenames that have an underscore in them.

When testing for files that already exist, this script:

#!/bin/bash
for name in bashrc bash_profile bash_aliases
do
  filename=$HOME"/."$name

  if [ -e "$filename" ]; then
    echo "${filename} exists"
  else
    echo "${filename} doesn't exist"
  fi
done

Outputs:

/home/xavier/.bashrc exists
/home/xavier/.bash_profile doesn't exist
/home/xavier/.bash_aliases doesn't exist

What is it about the underscore that is causing this behavior, and how do I fix it?

Upvotes: 0

Views: 1738

Answers (1)

that other guy
that other guy

Reputation: 123680

The code is correct as posted and underscore is not a problematic character in general.

You mention that you're symlinking the files -- if you're sure the files are there, verify that they are not broken symlinks. -e file will be false if the final target of the link doesn't exist.

Other things that can cause this are:

  • lacking permissions
  • invisible unicode characters like a zero-width space
  • similar-looking unicode characters like bаsh_profile which has a fullwidth low line instead of an underscore.
  • running the script in a chroot or sandbox
  • checking that the file exists in a different terminal than the one used for running the script -- it could be chrooted, SSH'd to another machine or started before a directory was mounted over the dir, and therefore have a different view of the fs

Upvotes: 1

Related Questions