Shell scripting

Table of contents

  1. Walking through directory trees
  2. Shell commands
  3. Error output
  4. Exit with status code
  5. Modules as main programs

Walking through directory trees

# List all files that have a specific filename extension.

use fs.tree: walk_files

function has_extension(file,s)
   return s==file[-len(s)..]
end

for file in walk_files("/")
   if has_extension(file,".txt")
      print(file)
   end
end


# The functional approach.

use fs.tree: walk_files

has_extension = |s| |file| s==file[-len(s)..]

(walk_files("/")
   .filter(has_extension(".txt"))
   .each(print))

Shell commands

# Execute a shell command, capture stdout
# and return it.

use sys.shell: sh

s = sh("GET en.wikipedia.org")
print(s)


# Don't capture stdout

sh("GET en.wikipedia.org",capture=false)


# With error handling

use sys.shell: sh, ShException

try
   s = sh("GET en.wikipedia.org")
   print(s)
catch e if e: ShException
   print("value: ",e.value)
   print("text: ",e.text)
end

Error output

use sys: eprint

# Directed to stdout.
print("Text")

# Directed to stderr.
eprint("Error message")

Exit with status code

use sys: exit

# Exit the program with a status code
# (0: success, 1: failure)
exit(1)

Modules as main programs

A module may show different behavior, depending on whether it is executed as the main program or loaded as a module. The function sys.main requests the runtime environment, whether the current code is run as the main program or not.

use sys

if sys.main()
   print("Module was executed as the main program.")
else
   print("Module was loaded from somewhere.")
end