Bash Script – Why Shortcut Cannot Access File Content?

bashcommand linescriptsshortcut-keys

I have a script that starts a new activity for hamster (activity tracker). This is my current script:

ACTIVITY=`zenity --entry --title "Enter new activity name" --text "New activity name:"`
hamster start $ACTIVITY

The problem is I would like the script to remember the last task so I can just run it with ENTER instead of typing the name again. I want it to store the name of it in file. Currently I have made the file manually: /usr/local/bin/hamster-log.

My script so far is the following:

file=/usr/local/bin/hamster-log
last=$(<$file)
activity=$(zenity --entry --title "Enter new activity name" --text "New activity name:" --entry-text "$last")
hamster start "$activity"
if [ ! -z "$activity" ]; then
    destdir=/some/directory/path/filename
    if [ -f "$file" ]; then
        echo "$activity" > "$file"
    fi
fi

The weird thing is when I run the script from terminal, it reads the file's content properly, but when I run it using a shortcut it doesn't read the file.

I have set the file's permissions to 777.

Best Answer

I'm not sure how you're calling the script in the custom shortcut but there are two possibilities:

  • You're calling an interpreter (e.g. sh /path/to/script): then you're calling sh or an incompatible shell: command substitutions such as $(<file) are replaced with the content of file only in Bash or compatible shells, so you may be calling an incompatible shell;
  • You're calling the script (e.g. /path/to/script): then the script doesn't have a shebang at the top.

So either:

  • If the first one, call the right interpreter (bash /path/to/script);
  • If the second one, add a shebang at the top of the script (#!/bin/bash).

Alternatively do something ugly (but POSIX and portable) such as:

last=$(cat "$file")
Related Question