0

We have simple Windows batch files that when an error occurs, an "ONCALL.bat" file is run to display support information that is maintained in a separate oncall.txt text file. This is our SOP.

ONCALL.BAT:

set scriptpath=%~dp0

TYPE "%scriptpath%oncall.txt"

I have zero experience with Unix and Shell scripts and I need to quickly provide a shell script equivalent to run in a Unix environment.

Could someone please provide me the .sh equivalent of this code?

Chad
  • 21,566
  • 46
  • 173
  • 299

2 Answers2

1
cat oncall.sh
#!/bin/bash
scriptpath=/path/to/scripts

cat ${scriptpath}/oncall.txt

After you create your file, it can't hurt to run

 dos2unix oncall.sh

Just to be sure there are no windows Ctrl-M chars that will totally mystify you with the way they can screw up Unix script processing.

THEN

 chmod 755 oncall.sh

To make the script executable.

confirm with

  ls -l oncall.sh

You should see listing like

-rwxr-xr-x 1 userName grpname  5263 Nov 21 14:44 oncall.sh

Finally, call the script with a full or relative path, i.e.

  ./oncall.sh

OR

  $PWD/oncall.sh

The first line is called the "shebang" line, and when your script is called, the OS reads the first line of the file, to find out what program to run to interpret the rest of the script file.

You may want/need to use as the first line "shebang" one of the following, but bash is a good guess

 #!/bin/ksh
 #!/bin/sh
 #!/bin/ash
 #!/bin/dash
 #!/bin/zsh

OR you may worst case, your shell lives in a non-standard directory, then you'll have to spell that out, i.e.

 #!/usr/bin/ksh

All shell support debugging arguments for trace and variable expansion like

  #!/bin/ksh -vx

Or you can wrap just certain lines to turn debugginng on and off like

  set -vx
   cat ${scriptpath}/oncall.txt
  set +vx

Given that

The ~dp special syntax between the % and the 0 basically says to expand the variable %0 to show the drive letter and path, which gives you the current directory containing the batch file!

I think /path/to/scripts is a reasonable substitute, scriptpath=$PWD would be a direct replacement, as there are no drive letters in Unix. The problem there, is that you either rely on unix PATH var to find your script or you cd /path/to/scripts and then run ./oncall.sh using the relative path./ to find the file without naving added a value to PATH.

IHTH.

shellter
  • 33,781
  • 7
  • 75
  • 89
  • [What does %~dp0 mean, and how does it work?](http://stackoverflow.com/questions/5034076/what-does-dp0-mean-and-how-does-it-work) – andrewdotn Nov 21 '12 at 20:14
1

Assuming that the help file and the script are in the same directory:

#!/bin/sh

SCRIPTPATH=`dirname "$0"`

cat "$SCRIPTPATH"/oncall.txt

$0 is the file path of the current script; the dirname command extracts the directory part of it. This way you can avoid using a hard-coded path for the help file within the script.

thkala
  • 76,870
  • 21
  • 145
  • 185