Skip to content
Advertisement

Unix shells: How to ensure command works against most common shells?

I have some java code which uses jsch to connect to our unix servers and run below command.

ls -lt /tempdirectory/ grep -v ‘^do | grep “$”(date ‘+%b %e’)” | head
-1 | awk ‘{print %9}’

Above command shows all files in the /tempdirectory in long format (the first pipe removes directories). From the result it then filters for all files which were created today (I.e. it greps for “Oct 16”). Since I did ls -lt the files are ordered by time, so when I pipe against head -1 I will get the latest file today. And then the last pipe will print the filename out

On a normal putty terminal, once I switch to bash shell, and run above command, it will correctly print out the latest file today.

But the default shell seems to be Bourne (-sh) which the above command will fail (and hence my code will fail)

Is there a way to create above command that is safe for common shells? I think the main shells I’ve seen at work are:

Bourne (sh)
Bourne again (bash)
Korn (ksh)

Advertisement

Answer

As per comments, I found the issue. Bourne cannot handle $(…) hence I needed to replace this with –> ` <— (not the regular apostrophes)

Reference:
https://www.unix.com/shell-programming-and-scripting/188983-syntax-error-line-24-unexpected.html

So the command becomes

ls -lt /tempdirectory/ | grep -v ‘^d’ | grep “date '+%b %e'” | head -1 | awk ‘{print $9}’

I dont whether this will work on many different shells but it seems to work on sh as well as bash

For some reason StackOverflow is not showing that apostrophe properly so I will clarify that I added the weird other apostrophe ` after the first double quote and before the last double quote in:

“{here}date ‘+%b %e'{here}”

(Also based on previous comments, it sounds like this is not just a matter of what shell you are using when determining command compatibility – your underlying OS may also have an impact. In my case, using uname -a shows i am using sunOS)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement