I would like to write a cross-platform script using shell so I can run it on linux, mac os and windows. I'm using cygwin on windows to make this possible. However, there are some custom commands that I need to execute on windows only. Is there a way to detect if the shell if running on windows in shell script? Thanks!
2 Answers
You can parse the output of the uname
command to determine the underlying OS.
-
-
Note that this won't work with Microsoft's Bash on Windows feature in Windows 10.
uname
reportsLinux
. Oct 5, 2016 at 1:33
Found a brilliant solution at https://nastytester.com/posts/script-that-works-in-windows-and-linux.html
Essentially, you're creating a bash function that will at the same time leverage the goto command from Windows CMD.
echo off
goto(){
# Linux code here
uname -o
}
goto $@
exit
:(){
rem Windows script here
echo %OS%
exit
If you require the passing of arguments, you can use my version here:
echo off
goto(){
# Linux code here
echo -n 'Found OS Type: '
uname -o
sleep 5
if [[ -z "$@" ]]; then
echo "No argument was detected. Project argument is required."
sleep 5
exit
else
./linux_launch.sh $@
fi
}
goto $@
echo "End of Linux function."
exit
:(){
rem Windows script here
echo.Found OS Type:
echo %OS%
set ARG=%1
echo %ARG%
if [%ARG%]==[] goto NOARG
timeout /t 5
start /wait cmd.exe /c ".\master_launch_1.bat %ARG%"
goto EOF
:NOARG
echo.No argument was detected. Project argument is required.
:EOF
echo.End of Windows function.
timeout /t 5