dbmitch dbmitch - 4 months ago 17
Bash Question

Bash syntax error

Just learning bash and trying to implement a function in a script.

The script below runs thru ShellCheck fine, but I get a syntax error running bash from the command line

It must be the way I've defined my function, but I can't figure out the right way to do it - especially if it passes ShellCheck

error is on line 24
syntax error near unexpected token `${\r''
`autounload() {



Script:


#!/bin/bash
# /home/pi/scripts/usb-unloader.sh
#
# Called from {SCRIPT_DIR}/usb-initloader.sh
# make sure to chmod 0755 on file
#
# UnMounts usb device on /media/<device>
# Logs changes to /var/log/syslog and local log folder
# use tail /var/log/syslog to look at latest events in log
#
# CONFIGURATION
#
LOG_FILE="$1"
MOUNT_DIR="$2"
DEVICE="$3" # USB device name (from kernel parameter passed from rule)
#
# check for defined log file
if [ -z "$LOG_FILE" ]; then
exit 1
fi
#
# autounload function to unmount USB device and remove mount folder
#
autounload() {
if [ -z "$MOUNT_DIR" ]; then
exit 1
fi
if [ -z "$DEVICE" ]; then
exit 1
fi

dt=$(date '+%Y-%m-%d %H:%M:%S')
echo "--- USB Auto UnLoader --- $dt"

sudo umount "/dev/$DEVICE"
sudo rmdir "$MOUNT_DIR/$DEVICE"

# test that this device isn't already mounted
device_mounted=$(grep "$DEVICE" /etc/mtab)

if ! "$device_mounted"; then
echo "/dev/$DEVICE successfully Un-Mounted"
exit 1
fi
}

autounload >> "$LOG_FILE" 2>&1


This is the part of the code where I start defining the function

#
autounload() {
if [ -z "$MOUNT_DIR" ]; then
exit 1
fi


I've tried to move function above and below where it gets called but it seems to makes no difference.

Answer

As discovered in comments, you have a Windows (DOS) file that then runs on a UNIX machine. This has the problem that the line endings in DOS are \r\n while in UNIX are \n, so there is a superfluous \r in every line.

To get rid of those you can use either of these:

Comments