user1650305
user1650305

Reputation:

RaspberryPI shutdown script

So I just recently hooked up my new Rasppi, and I wanted to write a script using shell scripts to easily shut down the board. From a single Google search, I learned that this command:

sudo shutdown -h now

Will shutdown the PI from the command line. Now I want to turn that into a script file that I can easily run. Is it as simple as pasting it into a text file and saving it as a shell script? Or am I missing something?

Upvotes: 1

Views: 4080

Answers (1)

erewok
erewok

Reputation: 7835

You could make a shell script for it, but typically, this is the kind of thing we make an alias for. Aliases are knicknames for common commands and they usually live in a .bashrc or .bash_profile in your home directory.

You declare aliases for all the commands you will commonly run. For instance, if you want to see colors every time you type ls, you should be able to include the following alias in your .bashrc:

alias ls='ls --color=auto'

Now every time you type ls, it's as if you've typed ls --color=auto.

So, then you could alias your shutdown command, but the sudo part makes it a bit tricky because sudo will overlook your .bashrc. Thus, you could do something like the following:

alias sudo='sudo '
alias turnoff='shutdown -h now'

You can call it whatever will be easy to remember. After you have edited your .bashrc file, you will have to source the file so the changes are remembered:

source ~/.bashrc

or:

. ~/.bashrc

After which, your command should probably be able to be run like so:

sudo turnoff

We're not saving much for keystrokes here, though, and what if you want to restart instead of halt or you want to shutdown in a few minutes (after it's done updating, for example)?

Alternately, since you asked about shell scripting, you could make a shell script, but when you create shell scripts, you will usually have to do a couple of things:

  1. Write your script and include a 'shebang' line at the top: #!/bin/bash (This tells your shell what will be used to run the script),
  2. chmod u+x your script to make it executable, and
  3. put it in your ~/bin/ directory (and make sure that directory is in your PATH).

You might also look up common .bashrc files, so you can see the kinds of stuff people often make aliases for (this is one of the first things we usually do when customizing a command-line environment).

For example,I still alias rm as rm -i, which asks me whenever I tell it to delete something and I only ever do rm -f if I'm really really sure I want to get rid of something. There are probably many here who would consider this silly, but I've lazily deleted lots of stuff in the past, and so I don't mind the safeguard.

Upvotes: 1

Related Questions