4

Is it possible to have a conditional within /etc/rc.local? I've checked many Q&As and most people suggest running chmod +x on it, but my problem is different. It actually does work for me without conditionals, but doesn't otherwise.

#!/bin/sh

if [[ -e /usr/src/an-existing-file ]]
then
    echo "seen" >> /etc/rclocalmadethis
fi

Here's the weird error I see when I run systemctl status rc-local.service:

rc.local[481]: /etc/rc.local: 3: /etc/rc.local: [[: not found

And here's my rc.local in the exact same location ls -lah /etc/:

-rwxr-xr-x  1 root root    292 Sep 19 09:13 rc.local

I'm on Debian 10 Standard.

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
aderchox
  • 631
  • 7
  • 13

3 Answers3

18

The [[ ... ]] syntax isn't valid for /bin/sh. Try:

if [ -e /usr/src/an-existing-file ]
then
    echo "seen" >> /etc/rclocalmadethis
fi

Note that sometimes it works because /bin/sh -> /bin/bash or some other shell that supports that syntax, but you can't depend on that being the case (as you see here).

You can run ls -l /bin/sh to get to know this info for instance:

lrwxrwxrwx 1 root root 4 Jul 18  2019 /bin/sh -> dash
roaima
  • 107,089
  • 14
  • 139
  • 261
Andy Dalton
  • 13,654
  • 1
  • 25
  • 45
3

[[ is a bash feature not available in sh:

root@d4b4b6325f2a:/# type [[
[[ is a shell keyword
root@d4b4b6325f2a:/# sh
# type [[
[[: not found
Arkadiusz Drabczyk
  • 25,049
  • 5
  • 53
  • 68
-1

In such circumstances, I would probably look at the test command.

/usr/bin/test -e /usr/src/an-existing-file && /bin/echo "seen" >> /etc/rclocalmadethis
ilkkachu
  • 133,243
  • 15
  • 236
  • 397
Bib
  • 2,056
  • 1
  • 4
  • 10
  • 2
    Well, yes, that bypasses the issue of `[[` vs. `[`, but doesn't tell why the code they tried here didn't work. In any case, `test` and `echo` are standard utilities, there's no need to write the full paths, just `test -e ... && echo ... ` would do. Or `if test -e ...; then echo ...; fi` – ilkkachu Sep 20 '20 at 18:45