Trending February 2024 # How To Evaluate Arithmetic Expressions In Bash? # Suggested March 2024 # Top 4 Popular

You are reading the article How To Evaluate Arithmetic Expressions In Bash? 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 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.

You're reading How To Evaluate Arithmetic Expressions In Bash?

How To Evaluate Hard And Soft Skills When Hiring

Regardless of the job, employees need both hard and soft skills to succeed in today’s workplace.

Hard skills and soft skills play off against each other. They help define the strengths of individuals and teams as well as how projects get tackled.

Knowing how to hire for certain hard and/or soft skills is essential to your company’s success.

This article is for small business owners and supervisors who want to learn more about hard and soft skills that employees must have and how to ensure that new hires are right for their business needs.

When making new hires, we typically have a good grasp on the skills we are looking for in candidates. However, we often focus heavily on the hard skills a candidate has and not as much on soft skills, even though well-rounded employees have both hard and soft skills. An employee with highly tuned technical skills will not necessarily be successful in a job unless they also possess people skills or the ability to work well within teams.

What are the differences between hard skills and soft skills?

Hard skills are tangible abilities workers have that help them do their jobs while soft skills are qualities or characteristics that can enhance workplace performance, improve company culture and support team members. Both are important as hiring a candidate that has both the necessary hard skills to fulfill their role and the right soft skills to complement your team is key.

Hard skills

Think of hard skills as more quantifiable and binary. You can generally measure the work product that results from hard skills’ capabilities ― for instance, the candidate either knows a computer program or does not.

These are some examples of hard skills:

The ability to type a certain number of words per minute

Knowledge of a computer program or skills relating to information technology support

Proficiency in a language

The ability to certify and run a machine or system that requires common training for operators

Data analysis

The ability to copywrite or edit documents

A specific degree, industry-recognized certifications, licensure or awards

Soft skills

Soft skills are the interpersonal abilities or personality traits that employees bring to the table. They are those intangible qualities that employers search for as they bring on new team members. An employee who is a technical expert in their field but lacks the soft skills to work well with others likely won’t be as beneficial to your company as someone who has those added traits.

Soft skills are also more diverse than hard skills. Here are some examples:

Effective communication skills

Expression of empathy for colleagues’ troubles and stress points

Self-awareness and the ability to “read the room”

Ability to work well in teams

Flexibility to pick up tasks and embrace changes in plans

Leadership qualities

Ability to manage time efficiently, such as meet deadlines and project targets on time

A solid and consistent work ethic

Attention to detail

Key Takeaway

Both hard and soft skills are essential to build a well-rounded organization. Hard skills are more tangible and quantifiable, while soft skills are more interpersonal and difficult to measure, although you certainly know when they are not present.

Tip

Building teams that incorporate a range of complementary hard and soft skill sets is a great way to ensure future balance and effectiveness of the team. Hard skills are easier and more tangible to measure and assess while soft skills are observable through more subjective analysis.

How to interview for hard and soft skills

In addition to what you search for on a resume, the interview questions you use to tease out candidates’ skill sets and other attributes are critical to determining who is most qualified to work for your company.

Employers often use skills assessments ― for both hard and soft skills ― to gauge the cumulative abilities and skill sets of current employees. These tests can also help you measure whether a candidate has the attributes to perform the job successfully.

Interviews and assessments: Hard skills

The most reliable way to assess hard skills is to employ a widely used skill assessment test that addresses industry- or job-specific tasks. These skill sets are easier to assess in a binary way. These are some common hard skill assessment tests:

Computer skills assessment

Work sample test

Cognitive ability test

Basic math or writing assessment

Interviews and assessment: Soft skills

The best assessment phase for skill sets is during the interview process. Develop questions that allow you to extract the information you need. You can find sample interview questions online to help you assess job candidates’ soft skills and attributes. Consider the STAR interview response technique. You can use it as a guide for effective questions to ask applicants:

Situation: Ask the applicant about a time they faced a difficult situation at work. Instruct them to provide enough context for you to understand the challenges they faced.

Task: Inquire about the tasks the candidate identified as necessary to address the situation. Ask them how they came up with these tasks and organized their time to address each.

Action: Learn more about how the candidate acted once they identified some constructive tasks they could take. Did they involve others or escalate the issue to management?

Result: Ask the candidate what the results of their actions were and what they learned from the experience. What might they have done differently knowing what they know now?

A candidate’s responses to questions that analyze a situation using the STAR method will reveal key things about their ability to analyze a situation critically, come up with solutions, plan tasks, organize their time and take appropriate action. It also demonstrates how well they reflect on their decisions, whether they’ve succeeded or failed and how they grow from handling challenges in the workplace.

Build your team with complementary skills

When recruiting candidates, it can be easy to determine whether they have the hard skills they require to do the job, but it’s also important to consider how their soft skills will complement your team. Recruiting and hiring people with the right combination of hard skills and soft skills can help level up your business in terms of both productivity and culture. When recruiting and hiring candidates, evaluating their hard skills and soft skills in context with your team’s can help you choose the best possible candidate.

Tejas Vemparala also contributed to this article.

How The Expressions Nft Marketplace Aims To Uplift Global Communities

Next week, the NFT platform Expressions — a marketplace dedicated to supporting underrepresented global art communities in Web3, will launch its genesis art project — Origins & Ancestries. The drop is the first of ten that will take place over the next year and will showcase 1,000 artworks from 12 artists in the Caribbean, including Sofía Maldonado-Suárez (Puerto Rico), Edward Bowen (Trinidad), Carlos Davila Rinaldi (Puerto Rico), Isabel Berenos (Curaçao), and more.

Expressions was created with an expansive goal in mind; Web3, for all its open-access rhetoric, remains frustratingly Western-focused, with North American and European artists dominating trends and headlines. To better shine a light on efforts to broaden the NFT ecosystem’s horizons, we spoke with JD Lasica, co-founder of Amberfi, the tech solutions platform behind Expressions, and Amberfi’s Director of Marketing and Community, Milena Rimassa, to talk about Expressions’ ambitions and why the NFT ecosystem needs to ensure all boats rise in its tide.

Expressions: a platform for global communities 

Like misconceptions of the gender imbalance in Web3, the stereotype of the crypto art space being composed of white men is an unfortunately persistent caricature. Similarly, the Black community in Web3 is doing amazing work in the space, with both artists and founders helping to carry the culturally diverse torch forward. 

Lasica and Rimassa are well aware of this fact and aim to prevent the repetition of inequities that are so common in the traditional art world.

“We feel really strongly that the Web3 space needs more diversity,” Lasica told nft now. “Not enough women are involved, not enough artists and creatives from underserved, unheard art communities are involved. Why can’t we have our ownership economy working in a way that benefits everybody?”

Credit: Carlos Davila Rinaldi

“There are so many artists all over this planet that were underrepresented in earlier iterations of the art world,” Rimassa said while speaking to nft now. “And there’s a lot of art that exists out there that can finally be monetized in ways to provide a sustainable living for others for marginalized groups.”

The artists taking part in Expressions’ inaugural drop, Origins & Ancestors, likewise believe Web3 can and should encapsulate a much wider spectrum of artists and cultures than it currently does.

“As an artist from Curaçao, it’s exciting to share my work alongside talented creators who are exploring themes of identity, culture, and heritage,” Berenos said in a press release shared with nft now. “Being a part of this project means more than just showcasing my art. It’s about contributing to a larger conversation about who we are and our origins.”

Building with artists in mind

Lasica and the Amberfi team have spent the last year talking to “thousands of creatives” around the globe to better understand what they want out of Web3 and how they’d like to engage with it. Most, he says, feel that the major NFT marketplaces out there aren’t serving their needs around intellectual property protection and ease of use. Expressions was built with these artists not only in mind but on board, with Lasica saying they regularly invite artists onto Zoom calls and Slack channels to “build the platform together.”

Credit:  Sofía Maldonado-Suárez

The platform will feature a one percent marketplace fee to sellers and a 1.9 percent fee to buyers on each NFT sold. Lasica and the team are trying to keep things relatively inexpensive on the marketplace while adding value in terms of curation and opportunities to artists to establish a footing in Web3. Benefits to creatives and collectors will include free mints, enforceable royalties, prices pegged to USD (payable via ETH, MATIC, or credit card), private workspaces for creators, and more.

Expressions’ season two drop is due in July and is set to feature 12 artists from the African continent. In the future, Expressions community members will be able to vote on the next geographical region the platform will focus on, with options including South Asia, South America, Aboriginal communities in Australia, First Nations, and more. For those interested in getting early access to the site, head to the platform’s Discord to learn more.

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.

3 Ways To Evaluate The Credibility Of A Source

Look for high-end, professional finishes to websites and print publications.

Note that this does not mean that all information found in well-packaged sources is credible. Templates for well-designed websites are inexpensive and easily available.

Where does the author work? Do they have credible work or study experience?

If the author is affiliated with a reputable institution or organization, what are its values and goals? Do they benefit financially by promoting a particular view?

What is his or her educational background?

What other works has the author published?

What experience does the author have? Are they an innovator, or a follower and promoter of the status quo? Is the author capable of representing the topic with a good structure?

Has this author been cited as a source by other scholars or experts in the field?

Check the date. Find out when the source was published or revised. In some subject areas, such as the sciences and technologies, having current sources is essential; but in other fields, like the humanities, including older material is critical. It’s also possible that you’re looking at an older version of the source, and an updated one has since been published. Check with a scholarly database for academic sources (or an online bookstore for popular sources) to see if a more recent version is available. If so, not only should you find it, but you can also feel more confident about the source — the more printings or editions, the more reliable the information.

The publishing company is almost as important as the author when evaluating the credibility of a source.

Determine the intended audience. Scan the document in question for tone, depth, and breadth before absorbing the information in it. Are those three elements appropriate for your project? Using a source that is too specialized and technical for your needs may lead you to misinterpret the information given, which is just as hurtful to your own credibility as using an unreliable source.

Check the reviews. You should make use of resources like Book Review Index, Book Review Digest, and Periodical Abstracts to determine how and why others have criticized the source. If there is significant controversy surrounding the validity of the source, you may wish to avoid using it, or examine it further with a skeptical eye.

Evaluate the source’s sources. Citing other reliable sources is a sign of credibility. It is, however, sometimes necessary to verify that the other sources also show a pattern of credibility and are used in context.

Be conscious of wording that indicates judgment. Conclusions that describe something as “bad or good” or “right or wrong” should be examined critically. It is more appropriate to compare something to an objective standard than to label it with words that represent abstract concepts — for example, “…these and other illegal acts…” is preferable to “…these and other despicable acts…”

The former describes the acts in terms of the law (an objective source) whereas the second example judges the actions according to the author’s own belief of what is a despicable act.

Evaluate consistency. Sources that apply different standards to those who agree and disagree with them are suspect. If your source praises one politician for “changing to meet the needs of his constituency” but criticizes an opposing politician for “changing his position with opinion polls,” then it is likely that the source is biased.

For example, the BMJ (formerly the British Medical Journal) banned all tobacco research funded by tobacco companies in 2013 because they determined that the special interests of the research funders would lead to biased, unreliable conclusions.[11]

Advertisement

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

Update the detailed information about How To Evaluate Arithmetic Expressions In Bash? 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!