DevOps/Shell

let [command]

게임이 더 좋아 2023. 1. 1. 14:54
반응형
728x170

let은 쉘 스크립팅을 할 때 많이 쓴다.

예시부터 보자

#!/bin/bash

# Declare variables
a=10
b=20

# Use the let command to perform arithmetic operations
let result=a+b
echo "$a + $b = $result"

let result=a-b
echo "$a - $b = $result"

let result=a*b
echo "$a * $b = $result"

let result=a/b
echo "$a / $b = $result"

let result=a%b
echo "$a % $b = $result"

 

??? let 없어도 result에 저장되는 것 아니야??

맞다. 그렇긴 하다.

하지만 그것은 연산이 아니라 문자열이 저장된다.

연산을 하기 위해서는 let을 써야한다.

다른 방법도 존재하긴 한다.

- expr x + y -> 사용도 높음

- $[x + y] -> 사용도 높음

-$((x + y)) -> 사용도 낮음

 

하지만 let을 연산 결과를 저장할 때 쓰인다.

사칙연산 뿐만 아니라 비트연산도 가능하다.

Logical도 가능함

#!/bin/bash

# Declare variables
a=10
b=20

# Use the let command to perform a bitwise AND operation
let result=a&b
echo "The result of $a & $b is $result"

# Use the let command to perform a bitwise OR operation
let result=a|b
echo "The result of $a | $b is $result"

# Use the let command to perform a bitwise XOR operation
let result=a^b
echo "The result of $a ^ $b is $result"

# Use the let command to shift the bits of a variable to the left
let result=a<<2
echo "The result of $a << 2 is $result"

# Use the let command to shift the bits of a variable to the right
let result=b>>2
echo "The result of $b >> 2 is $result"

 

for랑 합치면 더 유용하게 계산할 수도 있다.

#!/bin/bash

# Declare an array of values
values=(10 20 30 40 50)

# Use the for loop to iterate over the array
for value in ${values[@]}
do
  # Use the let command to perform arithmetic on the current value
  let result=value*2
  echo "$value * 2 = $result"
done

 

 

let을 쓸 때 옵션은 4가지 정도가 있다.

  • -x: This option causes the let command to display each arithmetic expression as it is executed, along with the result. This can be useful for debugging or for seeing how the let command is interpreting your expressions.
  • -f: This option disables the interpretation of certain characters as special shell characters. This can be useful if you want to treat these characters literally, rather than as shell commands or variables.
  • -i: This option causes the let command to treat all variables as integers, even if they contain non-integer values. This can be useful if you want to perform integer arithmetic on variables that may contain decimal values.
  • -t: This option causes the let command to display the result of each arithmetic expression in binary form. This can be useful if you want to see how the let command is interpreting binary values.

 

 

참고링크

https://phoenixnap.com/kb/bash-let

반응형
그리드형

'DevOps > Shell' 카테고리의 다른 글

Null Check  (0) 2023.01.01
exit  (0) 2023.01.01
environment variable  (0) 2022.12.31
Bash, 쉘 스크립트 시작하기  (0) 2022.12.25
Shell Script - 10, Function  (0) 2022.11.25