Trending February 2024 # How To Run Bash Script As Root During Startup On Linux # Suggested March 2024 # Top 6 Popular

You are reading the article How To Run Bash Script As Root During Startup On Linux updated in February 2024 on the website Achiashop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How To Run Bash Script As Root During Startup On Linux

Have you ever wanted to run a script at startup with root privileges? If you have a home server, or maybe even just a Linux desktop, this might have crossed your mind. This sounds iffy, but if you understand the risks, the reward for doing this can be quite good.

The main reasons are that there would be no more starting up the server, logging in over ssh, entering a password, getting a root shell and then manually executing script after script. Instead, harness the power of cron, and set your system to automatically run these scripts at startup! Here’s how to do it.

Tip: Check out our regular expressions cheatsheet.

Setting up Cron

Most Linux distributions come with the ability to access cron by just entering crontab -e. However, if you’ve entered this command, and nothing at all has happened, you’re on a Linux distribution that has no way to interact with cron. This means that you’ll need to install a tool to continue. The most popular tool to use in this situation is a daemon known as “cronie.” It’s a very popular tool and resides in most popular Linux distribution repositories.

Open up a terminal and install cronie with your package manager. Alternatively, head over to this page and download a package for your distribution.

Setting up the script with Cron

Opening a crontab is very easy. To start, open up a terminal window and enter the following command:

Note: the sudo is important if you want to run script as root. You can omit the sudo if you just want to run the script as a normal user.

If the system hasn’t used crontab before, the user will need to specify an editor to work with. Though all the editors are good in their own way, choose “nano” as it’s the simplest text editor and doesn’t require a lot of fussing with. With the editor selected, cron will load up a default file with detailed instructions as to how everything works.

Inside the nano editor in the terminal scroll all the way down to the bottom and start off by writing “@reboot.” The reboot command is key here as it tells the cron on reboot this command to run every single time. Directly after reboot, add the full file path to the bash script.

Now that the command is set up, the crontab can be saved. Press “Ctrl + o” on the keyboard. This will prompt the user to “write out the file.” By default, cron names the crontab, so don’t change anything. Press the enter key to save the crontab.

Remove the script from startup

In the same way that the command was added to the crontab, it can be removed. To do this, open up a terminal and enter sudo crontab -e. This will load the crontab file. Just delete the command that was added, save it, and restart the computer (or server).

Troubleshooting Cron

Sometimes cron doesn’t execute commands, and that can be a problem. The easiest way to troubleshoot any issues with cron (should there be any) is to look at the system log. To do that, open the terminal window and enter this command:

grep

CRON

/

var

/

log

/

syslog

The syslog shows all system events, and by using the grep command, it is possible to filter out what cron and crontag does. This should allow users to easily troubleshoot and fix anything that may go wrong.

Conclusion

Bash scripting is a wonderful thing, and its one of Linux’s great strengths. It makes administration of servers and even regular Linux computers easier because of the ability to take large amounts of commands and automate them. By adding cron to the picture, these scripts have the power to become even more useful. No more tinkering around after your Linux box boots. Just set it up and forget it!

What root scripts would you run at startup on your Linux box? Tell us below!

Derrik Diener

Derrik Diener is a freelance technology blogger.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Sign up for all newsletters.

By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. We will not share your data and you can unsubscribe at any time.

You're reading How To Run Bash Script As Root During Startup On Linux

Ensure Only One Instance Of A Bash Script Is Running On Linux

Introduction

When running a bash script on Linux, it’s important to ensure that only one instance of the script is running at a time. This is especially important for scripts that perform critical tasks, such as scripts that update databases or scripts that send email. Running multiple instances of the same script simultaneously can cause conflicts, data loss, and other errors. In this article, we will discuss different methods to ensure that only one instance of a bash script runs on Linux.

Using Flock

One way to ensure that only one instance of a bash script runs on Linux is to use the “flock” command. The flock command is used to create a lock on a file and is a command built into most shells such as Bash, Zsh, etc. It’s a simple and efficient way to ensure that only one instance of a script runs at a time.

We can trust this approach because there will be no race conditions. Also, all locks on a file are released when the process completes. These benefits make flocking a safe way to ensure that only one instance is running. Another benefit is that the flock program is an implementation of the flock system call.

flock by default blocks until the lock is released and then continues without errors. We can use the “-n” parameter to use flock in a non-blocking way. This will cause flock to exit immediately with an error when there is another lock on the file.

We can use flock to run an external script or use it inside the script.

Running an External Script

We can use flock in a script like this −

$ flock -n chúng tôi ./dobackup.sh

Now let’s assume that our script is currently running. Let’s see what happens if we execute the previous line again −

$ flock --verbose -n chúng tôi ./dobackup.sh flock: failed to get lock $ echo $? 1

We can see that flock informed us that it could not acquire the lock and exited with the value 1 (error). This means that another instance has the lock.

When flock fails, it does not run the script parameter, which prevents more than one instance of “dobackup.sh” from running.

Using Flock within the Script

We can use flock inside the script like this −

#!/bin/bash another_instance() { echo "There is another instance running, exiting" exit 1 }

In this case, we call flock with a file descriptor and enclose everything we need to protect in square brackets (a subshell) and redirect it to the file we use as lock. We call flock at the beginning with the file descriptor used in the redirect. So if flock exits with an error, we know there is another instance running.

Once the sublevel is finished, the lock file is closed and the lock is automatically released.

Using the Pid File

Another way to ensure that only one instance of a bash script runs on Linux is to use a pid file. A pid file is a special file that contains the process ID (PID) of the running script. By checking the pid file, we can determine if the script is already running and if so, exit the script with an error message.

To implement this method, we can add the following code to the beginning of our script −

if [ -f /path/to/pidfile ]; then pid=$(cat /path/to/pidfile) echo "Script is already running" exit 1 else fi else fi

At the end of the script, you can add the following code to remove the pid file −

$ rm -f /path/to/pidfile Conclusion

Running Script Or Command As Another User In Linux

There are several ways to run a script or command as another user in Linux. One way is to use the “su” command, which stands for “switch user.” For example, to run a command as the user “john,” you would use the following syntax: “su john -c ‘command'”

Another way to run a command as another user is to use the “sudo” command, which stands for “superuser do.” This command allows a user with proper permissions to run a command with the privileges of another user, typically the root user. For example, to run a command as the root user, you would use the following syntax: “sudo command”

You can also use the “runuser” command to run a command as another user, this command is similar to su command but it is more secure.

It’s important to note that using these commands can potentially be dangerous, as they allow a user to execute commands with escalated privileges. Therefore, it is important to use them with caution and only when necessary.

Using su

The “su” command is used to switch to another user’s account in Linux. The basic syntax for using the “su” command is as follows −

su [username]

For example, to switch to the “john” user, you would use the following command −

su john

When you run this command, you will be prompted to enter the password for the user you are switching to. Once you enter the correct password, you will be logged in as that user and will have the same privileges and permissions as that user.

You can also use the – option in order to switch to the previous user, for example −

su -

You can also run a command as another user by using the -c option followed by the command you want to run.

su john -c 'command'

It’s important to note that using “su” command can potentially be dangerous, as it allows a user to execute commands with escalated privileges. Therefore, it is important to use it with caution and only when necessary.

Using sudo

The “sudo” command is used to run a command with the privileges of another user, typically the root user, in Linux. The basic syntax for using the “sudo” command is as follows −

sudo [command]

For example, to run the “apt-get update” command as the root user, you would use the following command −

sudo apt-get update

When you run this command, you will be prompted to enter your own password. The system will then check if you have the necessary permissions to run the command as the root user. If you have the correct permissions, the command will be executed, otherwise, the command will be denied.

It’s important to note that running commands as the root user can be very dangerous if not done properly, as it allows a user to execute commands with escalated privileges. Therefore, it is important to use it with caution and only when necessary. And also, you should use sudo only for commands that require elevated privileges, not for every command.

Using runuser

The “runuser” command is used to run a command as another user in Linux, similar to the “su” command. The basic syntax for using the “runuser” command is as follows −

runuser [options] [username] [command]

For example, to run the command “ls -l” as the user “john”, you would use the following command −

runuser -l john -c 'ls -l'

The option -l is used to make the environment similar to a login shell and -c is used to specify the command that you want to run.

You can also use the -u option followed by the username to specify the user you want to run the command as −

runuser -u john ls -l

The “runuser” command is more secure than “su” command because it doesn’t start a shell and it doesn’t source any shell profile files which reduces the attack surface of the system.

It’s important to note that using the “runuser” command can potentially be dangerous, as it allows a user to execute commands with escalated privileges. Therefore, it is important to use it with caution and only when necessary.

Conclusion

There are several ways to run a script or command as another user in Linux, such as using the “su” command, the “sudo” command, or the “runuser” command. Each command has its own syntax and options, and it’s important to use them with caution and only when necessary.

The “su” command allows you to switch to another user’s account and run commands with that user’s privileges and permissions. The “sudo” command allows you to run a command with the privileges of the root user, but you need to have the correct permissions. And the “runuser” command allows you to run a command as another user, it is similar to su command but it is more secure as it doesn’t start a shell and it doesn’t source any shell profile files.

How To Disable Bloatware On Android — No Root Needed

Whenever I get a new phone, my first mission is to get rid of that pesky software manufacturers and carriers force into our devices. Yes, I am talking about bloatware, apps which come pre-installed on your new handset, that you will likely never use and often can’t uninstall.

Common bloatware apps include carrier services, cloud storage, sports apps, and games. But don’t worry, you may not always be able to uninstall Android bloatware, but there are ways to get unwanted apps out of your way. You don’t even need to tinker with the phone or gain root access. We’ll show you how to disable bloatware apps on Android, but we also want to discuss some alternatives that might be better solutions.

Editor’s note: Some of the instructions in this article were put together using a Pixel 4a with 5G running Android 12 (unless otherwise specified). Keep in mind steps may be different depending on your device and Android version.

Try uninstalling the bloatware app first

Edgar Cervantes / Android Authority

Manufacturers and carriers are known for installing bloatware on smartphones, but they don’t always force you to keep their apps. Now and then, you’ll be able to uninstall bloatware. While it isn’t common, simply uninstalling apps is worth trying. It just might work, and you won’t have to disable bloatware apps at all.

How to uninstall an app on Android:

Open the Settings app.

Go into Apps.

Select See all apps.

Find the application you want to delete and select it.

If it’s possible to get rid of the application, an Uninstall button will appear. Tap on it.

Confirm by hitting OK.

More: Multiple ways to uninstall apps on Android

Or just hide the app

Edgar Cervantes / Android Authority

The easiest way to clean up your app drawer is by hiding your apps. This used to be a feature we could only see in third-party launchers, which was heaven-sent for those of us who wanted to get rid of bloatware without having to root. The good news is some manufacturers have started baking this feature straight into their launchers, so you may not even need a third-party launcher to do this.

We can’t exactly tell you how to hide apps on your specific device, as this process is very different for every manufacturer and launcher, but it’s usually an option in the app drawer settings.

How to hide apps on Android:

Open the App Drawer.

Hit the 3-dot menu button in the top-right corner.

Select Settings.

Go to Hide apps.

Select the apps you want to hide.

Hit Done.

Note: These specific steps were put together using a Samsung Galaxy S10 Plus running Android 11. Steps might be different depending on your device and its software version. Also, some manufacturers don’t even offer the option.

The downside is that hiding apps doesn’t do much other than keep them out of sight. These apps may still run in the background and will take up space when hidden.

More: Android settings you should change

You can also try a third-party launcher

Have you ever checked out a third-party launcher? These make it possible to further customize the user interface. You can do things like resizing app grids, changing animations, moving elements around, and more. Of course, many of these also make it easy to hide bloatware apps.

Downloading a third-party launcher might be the best option if you want to hide an app without disabling it, and your phone’s stock interface doesn’t allow it. Each launcher has its own way of hiding apps, and not all include the feature, but we have some specific ones we prefer. Check them out below.

If nothing else works, then it’s time to try disabling bloatware apps.

How to disable apps

Edgar Cervantes / Android Authority

Disabling apps will ensure installed applications are not running in the background. Icons also won’t appear in your app drawer or home screens. The only issue is the app will continue to be on the phone, taking up storage space, but at least it won’t be draining other resources or cluttering your user interface. Furthermore, not all apps can be disabled. You’ll need to check.

How to disable bloatware apps on Android:

Open the Settings app.

Go to Apps.

Select See all apps.

Find the application you want to disable and select it.

If the app can be disabled, there will be a Disable button. Tap on it.

You should get a message warning about the risks of disabling an app. Hit Disable app if you’re OK with everything.

You are done! The app is now out of sight and no longer active.

Also try: How to stop Android apps from running in the background

While none of these methods are quite as satisfying as completely removing bloatware from a device, it is undoubtedly better than just leaving the apps enabled and eating away at your system resources. For those that want to take it to the next level, you can always root your phone and get completely rid of bloatware. Rooting your device isn’t as straightforward, though. Regardless, you can hit the link below if you want to learn more about rooting.

Next: Everything you need to know about rooting your Android phone

How To Install Git On Linux

Git is a popular version control system that enables developers to track changes in their codebase and quickly interact with others. It is widely used in the software development business and has evolved into an essential tool for many programmers.

In this article will walk you through the Installation of Git on Linux.

Prerequisites

Access to a user account that has sudo or root rights.

A computer that is running Ubuntu 20.04 or 22.04.

Access to a command line/terminal window (Ctrl+Alt+T).

Install Git using APT

This is the easiest way to install Git on your system because Git package is included in the official Ubuntu chúng tôi you wish to install a specific version or latest stable version, you need to Install Git from source.

[email protected]:-$ sudo apt update Yeading package lists... 99%

This command will refresh the package listings in preparation for upgrades and new package installations.

Then, if there are any pending upgrades, upgrade the system:

sudo apt upgrade [email protected]:-$ sudo apt upgrade Reading package lists... Done Building dependency tree... Done Reading state information... Done Calculating upgrade... Done The following packages were automatically installed and are no lon ger required: libflashromi libftdi1-2 1ibllvmi3 virtualbox-guest-utils Use 'sudo apt autoremove' to remove them. The following NEW packages will be installed: libatomic1 libllvmi5 linux-headers-5.19.0-45-generic linux-hwe-5.19-headers-5.19.0-45 linux-image-5.19.0-45-generic linux-modules-5.19.0-45-generic linux-modules-extra-5.19.0-45-generic systemd-hwe-hwdb The following packages will be upgraded: accountsservice alsa-ucm-conf apparmor apport apport-gtk apt apt-utils avahi-autoipd avahi-daemon avahi-utils base-files bind9-dnsutils bind9-host bindo-libs britty ca-certificates cpp-11 cups cups-browsed cups-bsd cups-client cups-common cups-core-drivers cups-daemon cups-filters cups-filters-core-drivers cups-ipp-utils cups-ppdc sudo apt install git [email protected]:-$ sudo apt install git Reading package lists... Done Building dependency tree... Done Reading state information... Done The following packages were automatically installed and are no nger required: Llibflashrom1 libftdi1-2 1ibllvm13 virtualbox-guest-utils Use 'sudo apt autoremove' to remove them. The following additional packages will be installed: git-man liberror-perl Suggested packages: git-gui gitk gitweb git-cvs git-mediawiki git-svn The following NEW packages will be installed: git git-man liberror-perl © upgraded, 3 newly installed, © to remove and 1 not upgraded. Need to get 4,147 kB of archives. After this operation, 21.6 MB of additional disk space will be used. Do you want to continue? [y/n]

During the installation, you may be asked to confirm the installation by typing ‘y’ and pressing Enter. Please do so in order for the installation to proceed. The system will then download and install the Git package and any dependencies.

git --version

If Git was successfully installed, the version number will be displayed in the output terminal.

Install Git from Source

If you wish to install a specific version of Git or any latest stable version, you need to compile Git from source. Make sure you install the dependencies required to install from source.

sudo apt update sudo apt install dh-autoreconf libcurl4-gnutls-dev libexpat1-dev make gettext libz-dev libssl-dev libghc-zlib-dev

Now choose the version you need to install and copy the tar.gz link from the official git releases page.

Now you can download and extract the version you wish to the /usr/share directory.

Once the download is completed you can move inside the directory and execute the following commands to compile and install Git.

.41.0.tar.gz

HTTP request sent, awaiting response… 362 Found

following] /tags/v2.41.0 3… connected. HTTP request sent, awaiting response… 260 OK Length: 10884275 (16M) [application/x-gzip] saving to: ‘STDOUT’

Here are the instructions for compiling and installing Git on Linux:

cd /usr/src/git-* sudo make prefix=/usr/local all sudo make prefix=/usr/local install [email protected]:~$ cd /usr/src/git-* sudo make prefix=/usr/Tocal all Sudo make prefix=/usr/Tocal install GIT_VERSION = 2.41.6 * new build flags CC oss-fuzz/fuzz-conmit-graph.o CC oss-fuzz/fuzz-pack-headers.o CC oss-fuzz/fuzz-pack-idx.o CC daemon.o * new link flags CC common-main.o cc abspath.o CC add-interactive.o CC add-patch.o CC alias.o CC alloc.o cc apply.o CC archive-tar.o cc archive-zip.o git --version

You will get a sample output similar to the one below.

Now you have compiled and installed Git from source.

Configure the Git User Information

Before you begin using Git, you should configure your user information. This data will be linked to any commits you make in a Git repository. Replace the placeholders with your own name and email address and run the following commands:

git config --global chúng tôi "Your Name" git config --global user.email "[email protected]"

You may check the configuration settings by running the command:

git config --list

A list of setup items, including your name and email address, will be displayed.

Output sample:

If you prefer to manually edit the Git configuration file, you can do so with any text editor you like, such as nano:

nano ~/.gitconfig

Now your changes will be saved inside the ~/.gitconfig folder.

Also read: You might also find useful our guide on How to Modify the Hostname in Linux

Conclusion

To summarize, installing Git on Linux is a simple process. By following the provided steps, you can easily set up Git, update your system, and configure your user information. You are now ready to use Git’s sophisticated version control capabilities for your software development projects after successfully installing it.

How To Evaluate Arithmetic Expressions In Bash?

Bash is a powerful programming language used for writing shell scripts on Linux and other Unix-based systems. One of most common tasks in shell scripting is evaluating arithmetic expressions. In this article, we will discuss how to evaluate arithmetic expressions in Bash and explore some examples.

Introduction

Arithmetic expressions are mathematical calculations performed on numerical values. In Bash, arithmetic expressions are evaluated using expr command, which evaluates a string as an arithmetic expression and returns result. syntax for expr command is as follows −

$ expr expression

Here, expression is arithmetic expression to be evaluated. For example, to evaluate expression 2 + 3, we would enter following command −

$ expr 2 + 3

This would return result 5.

Basic Arithmetic Operators

Bash supports all basic arithmetic operators, including addition, subtraction, multiplication, and division. These operators can be used to perform simple arithmetic calculations. table below shows basic arithmetic operators and their corresponding symbols.

Operator

Symbol

Addition

+

Subtraction

Multiplication

*

Division

/

Let’s look at some examples of using these basic arithmetic operators in Bash.

Example 1: Addition

To perform addition in Bash, we use + symbol. For example, to add 2 and 3, we would enter following command −

$ expr 2 + 3

This would return result 5.

Example 2: Subtraction

To perform subtraction in Bash, we use – symbol. For example, to subtract 3 from 5, we would enter following command −

$ expr 5 - 3

This would return result 2.

Example 3: Multiplication

To perform multiplication in Bash, we use * symbol. For example, to multiply 2 and 3, we would enter following command −

$ expr 2 * 3

Note that * symbol needs to be escaped with a backslash () to prevent it from being interpreted as a wildcard character by shell.

This would return result 6.

Example 4: Division

To perform division in Bash, we use / symbol. For example, to divide 6 by 2, we would enter following command −

$ expr 6 / 2

This would return result 3.

Order of Precedence

When evaluating arithmetic expressions in Bash, it is important to keep in mind order of precedence of arithmetic operators. order of precedence determines order in which operators are evaluated.

The order of precedence for basic arithmetic operators is as follows −

Multiplication and division (evaluated left to right)

Addition and subtraction (evaluated left to right)

For example, in expression 2 + 3 * 4, multiplication is evaluated first, and expression is evaluated as 2 + 12, which results in 14.

Let’s look at some examples of using order of precedence in Bash.

Example 5: Multiplication and Division

In expression 2 + 4 / 2 * 3, division is evaluated first, and expression is evaluated as 2 + 2 * 3, which results in 8. To evaluate expression as (2 + 4) / (2 * 3), we would use parentheses to group addition and multiplication −

$ expr 2+42+4 / 2*32*3

This would return result 1.

Example 6: Grouping with Parentheses

To group parts of an expression together, we can use parentheses. For example, in expression 2 * 3 + 4, we can group multiplication with parentheses to ensure it is evaluated first −

$ expr 2 * 3+43+4

This would return result 14.

Modulus Operator

In addition to basic arithmetic operators, Bash also supports modulus operator (%), which returns remainder of a division operation. For example, to calculate remainder when 5 is divided by 2, we would enter following command −

$ expr 5 % 2

This would return result 1.

Let’s look at an example of using modulus operator in Bash.

Example 7: Modulus Operator

In expression 17 % 4 + 3 * 2, modulus operation is evaluated first, and expression is evaluated as 1 + 6, which results in 7.

$ expr 17 % 4 + 3 * 2

This would return result 7.

Advanced Arithmetic Functions in Bash Square Roots

To calculate square root of a number in Bash, we use sqrt function. For example, to calculate square root of 16, we would enter following command −

$ expr sqrt 16

This would return result 4.

Exponents

To raise a number to a power in Bash, we use ** operator. For example, to calculate 2 raised to power of 3, we would enter following command −

$ expr 2 ** 3

This would return result 8.

Absolute Values

To calculate absolute value of a number in Bash, we use abs function. For example, to calculate absolute value of -5, we would enter following command −

$ expr abs -5

This would return result 5.

Using Variables in Arithmetic Expressions

In Bash, we can also use variables in arithmetic expressions. We can assign values to variables using = operator, and then use variables in arithmetic expressions. For example, to assign value 5 to a variable named x, we would enter following command −

$ x=5

We can then use variable in an arithmetic expression. For example, to add 2 to value of x, we would enter following command −

$ expr $x + 2

This would return result 7.

Conclusion

Evaluating arithmetic expressions is a common task in Bash scripting. By using expr command and basic arithmetic operators, as well as order of precedence and modulus operator, we can perform simple arithmetic calculations in Bash. With examples we’ve covered in this article, you should have a good understanding of how to evaluate arithmetic expressions in Bash and how to apply these concepts in your own scripts.

Update the detailed information about How To Run Bash Script As Root During Startup On Linux on the Achiashop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!