commands detail - i

if-then-else

The bash if-then-elif-else as per:

  1. HOUR_OF_DAY=$(date +'%H')
  2. if [ $HOUR_OF_DAY -lt 6 ]
  3. then
  4. echo "Still nightime"
  5. elif [ $HOUR_OF_DAY -lt 12 ]
  6. then
  7. echo "Morning has broken"
  8. elif [ $HOUR_OF_DAY -lt 18 ]
  9. then
  10. echo "After noon"
  11. else
  12. echo "Nightime again"
  13. fi

…could be rendered in PowerShell as:

  1. [int]$HourOfDay = $(get-date -UFormat '%H')
  2. if ( $HourOfDay -lt 6 )
  3. {
  4. write-output "Still nightime"
  5. }
  6. elseif ( $HourOfDay -lt 12 )
  7. {
  8. write-output "Morning has broken"
  9. }
  10. elseif ( $HourOfDay -lt 18 )
  11. {
  12. write-output "After noon"
  13. }
  14. else
  15. {
  16. write-output "Nightime again"
  17. }

if [ -f “$FileName” ]

Testing for the existence of a file in bash is done as follows

  1. export FileName=~/.matt
  2. if [ -f "$FileName" ]
  3. then
  4. echo "$FileName found."
  5. else
  6. echo "$FileName not found."
  7. fi

In PowerShell this could be[1]

  1. $FileName = "c:\powershell\.matt.ps1x"
  2. if (test-path $FileName)
  3. {echo "$FileName found"}
  4. else
  5. {echo "$FileName not found"}

Footnotes

[1] The way I’ve rendered the PowerShell here isn’t great, but I’ve left it like that because for a couple of reasons. First, it shows the similarity between PowerShell and Bash, which I think is encouraging for anyone reading this e-book. Second it allows me make a brief point about using aliases.

echo is handy. It’s short, and it looks like it does the same thing as echo in Unix, MS-DOS and probably a few other languages besides. It pretty much does…but does echo alias write-output which allows you to pipe to other PowerShell commands, or does it alias to write-host, which doesn’t?

I’ve been using PowerShell for a few years now but I didn’t know. I had to look it up. This is extra hassle if you’re reading a script, which is one of the reasons that it’s usually seen as being better practice in scripts to be explicit by using the full command rather than the alias.

Also, in PowerShell scripts rather than this:

  1. if (test-path $FileName)
  2. {write-host "$FileName found"}

…it would typically be seen as better to format using one of these two alternatives:

  1. if (test-path $FileName) {
  2. write-host "$FileName found"
  3. }

or:

  1. if (test-path $FileName)
  2. {
  3. write-host "$FileName found"
  4. }