How do you run a bash script?

I’m going through this book command line and shell scripting bible. Unfortunately I don’t really understand how it works.

In this examples I would make a file lets say ‘test’
In this file it would say

#!/bin/bash
#This script displays the date and who’s logged in
who
date

then I would save the file and type in chmod u+x test
giving my user permission to execute the file.
./test in ubuntu it worked

I tried looking other peoples topics on here and on the web but I’m too much of a noob to understand what their talking about. Is there a simple solution for this? I do understand nixos is preinstalled with sh shouldn’t i be able to change the nixos/configuration with bash instead? sorry for such a basic question.

I appreciate any help I get.

1 Like

Okay, sweet. I solved my own problem.

Anyone else the solution is to find the correct pathfile. I was trying to use pathfile from the store but It wasn’t working, regardless.
I installed it with nix-env -i bash
then went to /etc and cat shells found run/current-system/sw/bin/bash
So i replaced #!/bin/bash with #!/run/current-system/sw/bin/bash

You should use #!/usr/bin/env bash as shebang.

This version of the shebang is the most compatible one.

8 Likes

Thank you :slight_smile: Just curious how did you find that? what is env. the space in it. interesting

what is env. the space in it.

env is an command from the GNU coreutils bundle of commands (on NixOS), mostly commands you’d find in old UNIX and UNIX-like OSs. So it’s pretty old :slight_smile:

man env will tell you what it is, what it does and how to use it, although I must concede, these manual pages are often not really beginner friendly. I found that Wikipedia has a page dedicated to it! (env - Wikipedia).

Here /usr/bin/env bash is used to find an interpreter for bash scripts at runtime.

You can also use env to run other things than bash, like:

#!/usr/bin/env python3
print("Hello, World!")
2 Likes

Awesome, i appreciate you.

How would you pass in options using /usr/bin/env?

Some implementations of env, including the one that comes with NixOS by default, support a -S option, allowing you to do /usr/bin/env -S prog arg and run prog with arguments. It’s not specified in POSIX, though, so you can’t use it in scripts that you intend to be portable.

1 Like