Cross-platform shell scripts in V

V can be used as an alternative to Bash to write deployment scripts, build scripts, etc.

The advantage of using V for this is the simplicity and predictability of the language, and cross-platform support. “V scripts” run on Unix-like systems as well as on Windows.

Use the .vsh file extension. It will make all functions in the os module global (so that you can use mkdir() instead of os.mkdir(), for example).

An example deploy.vsh:

  1. // wip
  2. #!/usr/bin/env -S v run
  3. // The shebang above associates the file to V on Unix-like systems,
  4. // so it can be run just by specifying the path to the file
  5. // once it's made executable using `chmod +x`.
  6. // print command then execute it
  7. fn sh(cmd string){
  8. println("❯ $cmd")
  9. print(execute_or_exit(cmd).output)
  10. }
  11. // Remove if build/ exits, ignore any errors if it doesn't
  12. rmdir_all('build') or { }
  13. // Create build/, never fails as build/ does not exist
  14. mkdir('build')?
  15. // Move *.v files to build/
  16. result := execute('mv *.v build/')
  17. if result.exit_code != 0 {
  18. println(result.output)
  19. }
  20. sh('ls')
  21. // Similar to:
  22. // files := ls('.')?
  23. // mut count := 0
  24. // if files.len > 0 {
  25. // for file in files {
  26. // if file.ends_with('.v') {
  27. // mv(file, 'build/') or {
  28. // println('err: $err')
  29. // return
  30. // }
  31. // }
  32. // count++
  33. // }
  34. // }
  35. // if count == 0 {
  36. // println('No files')
  37. // }

Now you can either compile this like a normal V program and get an executable you can deploy and run anywhere: v deploy.vsh && ./deploy

Or just run it more like a traditional Bash script: v run deploy.vsh

On Unix-like platforms, the file can be run directly after making it executable using chmod +x: ./deploy.vsh