Rose Lancy

Rose Lancy

1591319579

How to Check if a Number is a BigInt in JavaScript

BigInt is a newer primitive type that can be used for integers of arbitrary size, unlike JavaScript’s default number type. Here’s how to check if you’re working with a BigInt, not a number.

#programming #javascript #mathematics #web-development

What is GEEK

Buddha Community

How to Check if a Number is a BigInt in JavaScript
Rupert  Beatty

Rupert Beatty

1684202959

How to Check The Number Of Arguments in The Bash Script

It is essential to count the total number of arguments that are passed to the script for various purposes such as error handling, providing messages based on the number of arguments, and helping the user to pass the correct number of arguments. The total number of arguments can be counted in Bash in two ways. One is using “$#” and another by using a loop. The methods of checking the number of arguments and using this value for different purposes are shown in this tutorial.

Different Uses of Checking the Number of Arguments

The uses of checking the number of arguments are shown in this part of the tutorial using multiple examples.

Example 1: Count the Total Number of Arguments Using “$#”

Create a Bash file with the following script that counts the total number of arguments and print the argument values using a “for” loop.

#!/bin/bash

#Store the number of arguments

len=$#

echo "Total number of arguments: $len"

echo "Argument values are:"

#Print the argument values

for val in $@

do

echo $val

done

The following output appears after executing the script with the argument values of 67, 34, and 12:

Example 2: Print the Argument Values Based on the Argument Length

Create a Bash file with the following script that counts the total number of arguments and print the argument values based on the number of arguments. An error message is printed if no argument is passed to the script.

#!/bin/bash

#Store the number of arguments

len=$#

#check the total number of arguments

if [ $len -eq 0 ]; then

echo "No argument is given"

fi

#initialize the counter

counter=0

#Print argument value based on the counter value

while (( $counter < $len ))

do

if [ $counter -lt 1 ]; then

echo $1

elif [ $counter -lt 2 ]; then

echo $2

elif [ $counter -lt 3 ]; then

echo $3

fi

((counter++))

done

The script is executed four times in the output. The error message is printed when no argument is given. The argument values are printed when one, two, and three argument values are given.

Example 3: Calculate the Average of the Argument Values

Create a Bash file with the following script that counts the total number of arguments and print the average value of five argument values. The “bc” command is used in the script to calculate the average value. An error message is printed if no argument is passed to the script.

#!/bin/bash

#Check the total number of arguments

if [ $# -eq 5 ]; then

#Calculate the sum of the argument values

sum=$(($1+$2+$3+$4+$5))

#Calculate the average values

avg=$(($sum/5 | bc -l))

#Print the average values and the argument values

echo "Arguments values are: $1 $2 $3 $4 $5"

echo "Average value: $avg"

else

#Print error message

echo "Total number of arguments must be 5."

fi

The script is executed twice in the output. The error message is printed when no argument is given. The average of the argument values are printed when five argument values are given.

Example 4: Print the Error Message Based on the Argument Values

Create a Bash file with the following script that prints any of the three messages based on the “if” condition. The first “if” condition checks whether the number of arguments is 2 or not. The second “if” condition checks whether the length of the argument value is less than 5 or not. The third “if” condition checks whether the second argument is positive or not.

#!/bin/bash

#Read the argument values

name=$1

price=$2

#Count the length of the second argument

len=${#name}

#Check the total number of arguments

if [ $# -ne 2 ]; then

echo "Total number of arguments must be 2."

exit

#Check the length of the first argument

elif [ $len -lt 5 ]; then

echo "Product name must be minimum 5 characters long."

exit

#Check the value of the second argument

elif [ $2 -lt 0 ]; then

echo "The price value must be positive."

exit

fi

#Print the argument values

echo "The price of $name is TK. $price"

The script is executed four times in the output. The error message, “Total number of arguments must be 2”, is printed when no argument is given. The error message, “Product name must be minimum 5 characters long”, is printed when the length of the first argument is less than five. The error message, “The price value must be positive”, is printed when the second argument is negative.

Conclusion

The uses of the number of arguments in the Bash script for various purposes are shown in this tutorial using multiple examples to help the new Bash users.

Original article source at: https://linuxhint.com/

#bash #script #number #arguments 

Rupert  Beatty

Rupert Beatty

1684207573

How to Check If The File Exists in Bash

Different types of files are used in Bash for different purposes. Many options are available in Bash to check if the particular file exists or not. The existence of the file can be checked using the file test operators with the “test” command or without the “test” command. The purposes of different types of file test operators to check the existence of the file are shown in this tutorial.

File Test Operators

Many file test operators exist in Bash to check if a particular file exists or not. Some of them are mentioned in the following:

OperatorPurpose
-fIt is used to check if the file exists and if it is a regular file.
-dIt is used to check if the file exists as a directory.
-eIt is used to check the existence of the file only.
-h or -LIt is used to check if the file exists as a symbolic link.
-rIt is used to check if the file exists as a readable file.
-wIt is used to check if the file exists as a writable file.
-xIt is used to check if the file exists as an executable file.
-sIt is used to check if the file exists and if the file is nonzero.
-bIt is used to check if the file exists as a block special file.
-cIt is used to check if the file exists as a special character file.

Different Examples to Check Whether the File Exists or Not

Many ways of checking the existence of the regular file are shown in this part of the tutorial.

Example 1: Check the Existence of the File Using the -F Operator with Single Third Brackets ([])

Create a Bash file with the following script that takes the filename from the user and check whether the file exists in the current location or not using the -f operator in the “if” condition with the single third brackets ([]).

#!/bin/bash

#Take the filename

echo -n "Enter the filename: "

read filename

#Check whether the file exists or not using the -f operator

if [ -f "$filename" ]; then

echo "File exists."

else

echo "File does not exist."

fi

The script is executed twice in the following script. The non-existence filename is given in the first execution. The existing filename is given in the second execution. The “ls” command is executed to check whether the file exists or not.

Example 2: Check the Existence of the File Using the -F Operator with Double Third Brackets ([[ ]])

Create a Bash file with the following script that takes the filename as a command-line argument and check whether the file exists in the current location or not using the -f operator in the “if” condition with the double third brackets ([[ ]]).

#!/bin/bash

#Take the filename from the command-line argument

filename=$1

#Check whether the argument is missing or not

if [ "$filename" != "" ]; then

#Check whether the file exists or not using the -f operator

if [[ -f "$filename" ]]; then

echo "File exists."

else

echo "File does not exist."

fi

else

echo "Argument is missing."

fi

The script is executed twice in the following script. No argument is given in the first execution. An existing filename is given as an argument in the second execution. The “ls” command is executed to check whether the file exists or not.

Example 3: Check the Existence of the File Using the -F Operator with the “Test” Command

Create a Bash file with the following script that takes the filename as a command-line argument and check whether the file exists in the current location or not using the -f operator with the “test” command in the “if” condition.

#!/bin/bash

#Take the filename from the command-line argument

filename=$1

#Check whether the argument is missing or not

if [ $# -lt 1 ]; then

echo "No argument is given."

exit 1

fi

#Check whether the file exists or not using the -f operator

if test -f "$filename"; then

echo "File exists."

else

echo "File does not exist."

fi

The script is executed twice in the following script. No argument is given in the first execution. An existing filename is given in the second execution.

Example 4: Check the Existence of the File with the Path

Create a Bash file with the following script that checks whether the file path exists or not using the -f operator with the “test” command in the “if” condition.

#!/bin/bash

#Set the filename with the directory location

filename='temp/courses.txt'

#Check whether the file exists or not using the -f operator

if test -f "$filename"; then

echo "File exists."

else

echo "File does not exist."

fi

The following output appears after executing the script:

Conclusion

The methods of checking whether a regular file exists or not in the current location or the particular location are shown in this tutorial using multiple examples.

Original article source at: https://linuxhint.com/

#bash #file 

Как проверить количество аргументов в скрипте Bash

Важно подсчитать общее количество аргументов, которые передаются сценарию для различных целей, таких как обработка ошибок, предоставление сообщений на основе количества аргументов и помощь пользователю в передаче правильного количества аргументов. Общее количество аргументов можно подсчитать в Bash двумя способами. В одном используется «$#», а в другом — цикл. В этом руководстве показаны методы проверки количества аргументов и использования этого значения для различных целей.

Различные варианты использования проверки количества аргументов

Использование проверки количества аргументов показано в этой части руководства на нескольких примерах.

Пример 1. Подсчет общего количества аргументов с использованием «$#»

Создайте файл Bash со следующим сценарием, который подсчитывает общее количество аргументов и печатает значения аргументов, используя цикл for.

#!/bin/bash

#Store the number of arguments

len=$#

echo "Total number of arguments: $len"

echo "Argument values are:"

#Print the argument values

for val in $@

do

echo $val

done

Следующий вывод появляется после выполнения скрипта со значениями аргументов 67, 34 и 12:

Пример 2. Печать значений аргумента на основе длины аргумента

Создайте файл Bash со следующим сценарием, который подсчитывает общее количество аргументов и печатает значения аргументов в зависимости от количества аргументов. Сообщение об ошибке печатается, если сценарию не передается аргумент.

#!/bin/bash

#Store the number of arguments

len=$#

#check the total number of arguments

if [ $len -eq 0 ]; then

echo "No argument is given"

fi

#initialize the counter

counter=0

#Print argument value based on the counter value

while (( $counter < $len ))

do

if [ $counter -lt 1 ]; then

echo $1

elif [ $counter -lt 2 ]; then

echo $2

elif [ $counter -lt 3 ]; then

echo $3

fi

((counter++))

done

Сценарий выполняется четыре раза на выходе. Сообщение об ошибке выводится, если аргумент не указан. Значения аргументов печатаются, когда заданы одно, два и три значения аргумента.

Пример 3. Вычисление среднего значения аргумента

Создайте файл Bash со следующим сценарием, который подсчитывает общее количество аргументов и печатает среднее значение пяти значений аргументов. Команда «bc» используется в скрипте для вычисления среднего значения. Сообщение об ошибке печатается, если сценарию не передается аргумент.

#!/bin/bash

#Check the total number of arguments

if [ $# -eq 5 ]; then

#Calculate the sum of the argument values

sum=$(($1+$2+$3+$4+$5))

#Calculate the average values

avg=$(($sum/5 | bc -l))

#Print the average values and the argument values

echo "Arguments values are: $1 $2 $3 $4 $5"

echo "Average value: $avg"

else

#Print error message

echo "Total number of arguments must be 5."

fi

Сценарий выполняется дважды на выходе. Сообщение об ошибке выводится, если аргумент не указан. Среднее значение аргумента печатается, когда задано пять значений аргумента.

Пример 4. Печать сообщения об ошибке на основе значений аргументов

Создайте файл Bash со следующим сценарием, который печатает любое из трех сообщений на основе условия «если». Первое условие «если» проверяет, равно ли число аргументов 2 или нет. Второе условие «если» проверяет, меньше ли длина значения аргумента 5 или нет. Третье условие «если» проверяет, является ли второй аргумент положительным или нет.

#!/bin/bash

#Read the argument values

name=$1

price=$2

#Count the length of the second argument

len=${#name}

#Check the total number of arguments

if [ $# -ne 2 ]; then

echo "Total number of arguments must be 2."

exit

#Check the length of the first argument

elif [ $len -lt 5 ]; then

echo "Product name must be minimum 5 characters long."

exit

#Check the value of the second argument

elif [ $2 -lt 0 ]; then

echo "The price value must be positive."

exit

fi

#Print the argument values

echo "The price of $name is TK. $price"

Сценарий выполняется четыре раза на выходе. Сообщение об ошибке «Общее количество аргументов должно быть равно 2» выводится, если аргумент не указан. Сообщение об ошибке «Название продукта должно содержать не менее 5 символов» печатается, когда длина первого аргумента меньше пяти. Сообщение об ошибке «Значение цены должно быть положительным» печатается, когда второй аргумент отрицательный.

Заключение

Использование количества аргументов в сценарии Bash для различных целей показано в этом руководстве с использованием нескольких примеров, чтобы помочь новым пользователям Bash.

Оригинальный источник статьи: https://linuxhint.com/

#bash #script #number #arguments 

如何在 Bash 中检查文件是否存在

Bash 中出于不同的目的使用不同类型的文件。Bash 中有许多选项可用于检查特定文件是否存在。可以使用带有“test”命令或不带有“test”命令的文件测试操作符来检查文件是否存在。本教程显示了不同类型的文件测试操作符检查文件是否存在的目的。

文件测试操作员

Bash 中存在许多文件测试运算符来检查特定文件是否存在。下面提到了其中一些:

操作员目的
-F它用于检查文件是否存在以及它是否是常规文件。
-d它用于检查文件是否作为目录存在。
-e它仅用于检查文件是否存在。
-h 或 -L它用于检查文件是否作为符号链接存在。
-r它用于检查文件是否作为可读文件存在。
-w它用于检查文件是否作为可写文件存在。
-X它用于检查文件是否作为可执行文件存在。
-s它用于检查文件是否存在以及文件是否为非零。
-b它用于检查文件是否作为块特殊文件存在。
-C它用于检查文件是否作为特殊字符文件存在。

检查文件是否存在的不同示例

本教程的这一部分显示了许多检查常规文件是否存在的方法。

示例 1:使用带有单个三分括号 ([]) 的 -F 运算符检查文件是否存在

使用以下脚本创建一个 Bash 文件,该脚本从用户那里获取文件名,并在“if”条件中使用带有第三个括号 ([]) 的 -f 运算符检查文件是否存在于当前位置。

#!/bin/bash

#Take the filename

echo -n "Enter the filename: "

read filename

#Check whether the file exists or not using the -f operator

if [ -f "$filename" ]; then

echo "File exists."

else

echo "File does not exist."

fi

该脚本在以下脚本中执行了两次。不存在的文件名在第一次执行时给出。现有文件名在第二次执行时给出。执行“ls”命令来检查文件是否存在。

示例 2:使用带有双三分括号 ([[ ]]) 的 -F 运算符检查文件是否存在

使用以下脚本创建一个 Bash 文件,该脚本将文件名作为命令行参数,并在“if”条件中使用 -f 运算符和双第三括号 ([[ ] ]).

#!/bin/bash

#Take the filename from the command-line argument

filename=$1

#Check whether the argument is missing or not

if [ "$filename" != "" ]; then

#Check whether the file exists or not using the -f operator

if [[ -f "$filename" ]]; then

echo "File exists."

else

echo "File does not exist."

fi

else

echo "Argument is missing."

fi

该脚本在以下脚本中执行了两次。第一次执行时不给出参数。在第二次执行中,将现有文件名作为参数给出。执行“ls”命令来检查文件是否存在。

示例 3:使用带有“测试”命令的 -F 运算符检查文件是否存在

使用以下将文件名作为命令行参数的脚本创建 Bash 文件,并在“if”条件下使用 -f 运算符和“test”命令检查文件是否存在于当前位置。

#!/bin/bash

#Take the filename from the command-line argument

filename=$1

#Check whether the argument is missing or not

if [ $# -lt 1 ]; then

echo "No argument is given."

exit 1

fi

#Check whether the file exists or not using the -f operator

if test -f "$filename"; then

echo "File exists."

else

echo "File does not exist."

fi

该脚本在以下脚本中执行了两次。第一次执行时不给出参数。第二次执行时给出一个现有的文件名。

示例 4:使用路径检查文件是否存在

使用以下脚本创建 Bash 文件,在“if”条件下使用 -f 运算符和“test”命令检查文件路径是否存在。

#!/bin/bash

#Set the filename with the directory location

filename='temp/courses.txt'

#Check whether the file exists or not using the -f operator

if test -f "$filename"; then

echo "File exists."

else

echo "File does not exist."

fi

执行脚本后出现如下输出:

结论

本教程通过多个示例展示了检查当前位置或特定位置是否存在常规文件的方法。

文章原文出处:https: //linuxhint.com/

#bash #file 

如何检查 Bash 脚本中的参数数量

出于各种目的(例如错误处理、根据参数数量提供消息以及帮助用户传递正确数量的参数),必须计算传递给脚本的参数总数。在 Bash 中可以通过两种方式计算参数总数。一种是使用“$#”,另一种是使用循环。本教程介绍了检查参数数量和将此值用于不同目的的方法。

检查参数个数的不同用途

本教程的这一部分使用多个示例展示了检查参数数量的用途。

示例 1:使用“$#”计算参数总数

使用以下脚本创建一个 Bash 文件,该脚本计算参数总数并使用“for”循环打印参数值。

#!/bin/bash

#Store the number of arguments

len=$#

echo "Total number of arguments: $len"

echo "Argument values are:"

#Print the argument values

for val in $@

do

echo $val

done

使用参数值 67、34 和 12 执行脚本后出现以下输出:

示例 2:根据参数长度打印参数值

使用以下脚本创建一个 Bash 文件,该脚本计算参数总数并根据参数数量打印参数值。如果没有参数传递给脚本,则会打印一条错误消息。

#!/bin/bash

#Store the number of arguments

len=$#

#check the total number of arguments

if [ $len -eq 0 ]; then

echo "No argument is given"

fi

#initialize the counter

counter=0

#Print argument value based on the counter value

while (( $counter < $len ))

do

if [ $counter -lt 1 ]; then

echo $1

elif [ $counter -lt 2 ]; then

echo $2

elif [ $counter -lt 3 ]; then

echo $3

fi

((counter++))

done

该脚本在输出中执行了四次。没有给出参数时打印错误消息。当给出一个、两个和三个参数值时,将打印参数值。

示例 3:计算参数值的平均值

使用以下脚本创建 Bash 文件,计算参数总数并打印五个参数值的平均值。脚本中使用“bc”命令计算平均值。如果没有参数传递给脚本,则会打印一条错误消息。

#!/bin/bash

#Check the total number of arguments

if [ $# -eq 5 ]; then

#Calculate the sum of the argument values

sum=$(($1+$2+$3+$4+$5))

#Calculate the average values

avg=$(($sum/5 | bc -l))

#Print the average values and the argument values

echo "Arguments values are: $1 $2 $3 $4 $5"

echo "Average value: $avg"

else

#Print error message

echo "Total number of arguments must be 5."

fi

该脚本在输出中执行了两次。没有给出参数时打印错误消息。当给出五个参数值时,打印参数值的平均值。

示例 4:根据参数值打印错误消息

使用以下脚本创建一个 Bash 文件,该脚本根据“if”条件打印三个消息中的任何一个。第一个“if”条件检查参数的数量是否为 2。第二个“if”条件检查参数值的长度是否小于 5。第三个“if”条件检查第二个参数是否为正。

#!/bin/bash

#Read the argument values

name=$1

price=$2

#Count the length of the second argument

len=${#name}

#Check the total number of arguments

if [ $# -ne 2 ]; then

echo "Total number of arguments must be 2."

exit

#Check the length of the first argument

elif [ $len -lt 5 ]; then

echo "Product name must be minimum 5 characters long."

exit

#Check the value of the second argument

elif [ $2 -lt 0 ]; then

echo "The price value must be positive."

exit

fi

#Print the argument values

echo "The price of $name is TK. $price"

该脚本在输出中执行了四次。没有给出参数时会打印错误消息“参数总数必须为 2”。当第一个参数的长度小于五个时,将打印错误消息“产品名称的长度必须至少为 5 个字符”。当第二个参数为负数时,将打印错误消息“价格值必须为正数”。

结论

本教程使用多个示例展示了 Bash 脚本中参数数量的各种用途,以帮助新的 Bash 用户。

文章原文出处:https: //linuxhint.com/

#bash #script #number #arguments