https://github.com/greatscottgadgets/hackrf

 

GitHub - greatscottgadgets/hackrf: low cost software radio platform

low cost software radio platform. Contribute to greatscottgadgets/hackrf development by creating an account on GitHub.

github.com

 

Prerequisites for Linux (Debian/Ubuntu):

$ sudo apt-get install build-essential cmake libusb-1.0-0-dev pkg-config libfftw3-dev

 

Build host software on Linux:

cmake ..

~/dev/hackrf$ mkdir host/build
~/dev/hackrf$ cd host/build
~/dev/hackrf/host/build$ cmake ..

CMake Deprecation Warning at CMakeLists.txt:3 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


-- The C compiler identification is GNU 11.4.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
CMake Deprecation Warning at libhackrf/CMakeLists.txt:24 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.2")
-- Checking for module 'libusb-1.0'
--   Found libusb-1.0, version 1.0.25
CMake Warning (dev) at /usr/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake:438 (message):
  The package name passed to `find_package_handle_standard_args` (LIBUSB)
  does not match the name of the calling package (USB1).  This can lead to
  problems in calling code that expects `find_package` result variables
  (e.g., `_FOUND`) to follow a certain pattern.
Call Stack (most recent call first):
  cmake/modules/FindUSB1.cmake:39 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  libhackrf/CMakeLists.txt:48 (find_package)
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Found LIBUSB: /usr/lib/x86_64-linux-gnu/libusb-1.0.so
-- Looking for include file pthread.h
-- Looking for include file pthread.h - found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Setting udev rule group to - plugdev
-- HackRF udev rules will be installed to '/etc/udev/rules.d' upon running 'make install'
CMake Deprecation Warning at hackrf-tools/CMakeLists.txt:24 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


-- Found FFTW: /usr/lib/x86_64-linux-gnu/libfftw3f.so
-- Configuring done
-- Generating done
-- Build files have been written to: /home/{user}/dev/hackrf/host/build

make

~/dev/hackrf/host/build$ make
[  5%] Building C object libhackrf/src/CMakeFiles/hackrf.dir/hackrf.c.o
[ 10%] Linking C shared library libhackrf.so
[ 10%] Built target hackrf
[ 15%] Building C object libhackrf/src/CMakeFiles/hackrf-static.dir/hackrf.c.o
[ 20%] Linking C static library libhackrf.a
[ 20%] Built target hackrf-static
[ 25%] Building C object hackrf-tools/src/CMakeFiles/hackrf_transfer.dir/hackrf_transfer.c.o
[ 30%] Linking C executable hackrf_transfer
[ 30%] Built target hackrf_transfer
[ 35%] Building C object hackrf-tools/src/CMakeFiles/hackrf_spiflash.dir/hackrf_spiflash.c.o
[ 40%] Linking C executable hackrf_spiflash
[ 40%] Built target hackrf_spiflash
[ 45%] Building C object hackrf-tools/src/CMakeFiles/hackrf_cpldjtag.dir/hackrf_cpldjtag.c.o
[ 50%] Linking C executable hackrf_cpldjtag
[ 50%] Built target hackrf_cpldjtag
[ 55%] Building C object hackrf-tools/src/CMakeFiles/hackrf_info.dir/hackrf_info.c.o
[ 60%] Linking C executable hackrf_info
[ 60%] Built target hackrf_info
[ 65%] Building C object hackrf-tools/src/CMakeFiles/hackrf_debug.dir/hackrf_debug.c.o
[ 70%] Linking C executable hackrf_debug
[ 70%] Built target hackrf_debug
[ 75%] Building C object hackrf-tools/src/CMakeFiles/hackrf_clock.dir/hackrf_clock.c.o
[ 80%] Linking C executable hackrf_clock
[ 80%] Built target hackrf_clock
[ 85%] Building C object hackrf-tools/src/CMakeFiles/hackrf_sweep.dir/hackrf_sweep.c.o
[ 90%] Linking C executable hackrf_sweep
[ 90%] Built target hackrf_sweep
[ 95%] Building C object hackrf-tools/src/CMakeFiles/hackrf_operacake.dir/hackrf_operacake.c.o
[100%] Linking C executable hackrf_operacake
[100%] Built target hackrf_operacake

sudo make install

~/dev/hackrf/host/build$ sudo make install
Consolidate compiler generated dependencies of target hackrf
[ 10%] Built target hackrf
Consolidate compiler generated dependencies of target hackrf-static
[ 20%] Built target hackrf-static
Consolidate compiler generated dependencies of target hackrf_transfer
[ 30%] Built target hackrf_transfer
Consolidate compiler generated dependencies of target hackrf_spiflash
[ 40%] Built target hackrf_spiflash
Consolidate compiler generated dependencies of target hackrf_cpldjtag
[ 50%] Built target hackrf_cpldjtag
Consolidate compiler generated dependencies of target hackrf_info
[ 60%] Built target hackrf_info
Consolidate compiler generated dependencies of target hackrf_debug
[ 70%] Built target hackrf_debug
Consolidate compiler generated dependencies of target hackrf_clock
[ 80%] Built target hackrf_clock
Consolidate compiler generated dependencies of target hackrf_sweep
[ 90%] Built target hackrf_sweep
Consolidate compiler generated dependencies of target hackrf_operacake
[100%] Built target hackrf_operacake
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/lib/pkgconfig/libhackrf.pc
-- Installing: /etc/udev/rules.d/53-hackrf.rules
-- Installing: /usr/local/lib/libhackrf.so.0.8.0
-- Installing: /usr/local/lib/libhackrf.so.0
-- Installing: /usr/local/lib/libhackrf.so
-- Installing: /usr/local/lib/libhackrf.a
-- Installing: /usr/local/include/libhackrf/hackrf.h
-- Installing: /usr/local/bin/hackrf_transfer
-- Set runtime path of "/usr/local/bin/hackrf_transfer" to ""
-- Installing: /usr/local/bin/hackrf_spiflash
-- Set runtime path of "/usr/local/bin/hackrf_spiflash" to ""
-- Installing: /usr/local/bin/hackrf_cpldjtag
-- Set runtime path of "/usr/local/bin/hackrf_cpldjtag" to ""
-- Installing: /usr/local/bin/hackrf_info
-- Set runtime path of "/usr/local/bin/hackrf_info" to ""
-- Installing: /usr/local/bin/hackrf_debug
-- Set runtime path of "/usr/local/bin/hackrf_debug" to ""
-- Installing: /usr/local/bin/hackrf_clock
-- Set runtime path of "/usr/local/bin/hackrf_clock" to ""
-- Installing: /usr/local/bin/hackrf_sweep
-- Set runtime path of "/usr/local/bin/hackrf_sweep" to ""
-- Installing: /usr/local/bin/hackrf_operacake
-- Set runtime path of "/usr/local/bin/hackrf_operacake" to ""

sudo ldconfig

~/dev/hackrf/host/build$ sudo ldconfig
/sbin/ldconfig.real: /usr/lib/wsl/lib/libcuda.so.1 is not a symbolic link

By default this will attempt to install an udev rule to /etc/udev/rules.d

 to provide the the usb or plugdev group access to HackRF.

If your setup requires the udev rule to be installed elsewhere

 you can modify the path with -DUDEV_RULES_PATH=/path/to/udev.

Note: The udev rule is not installed by default for PyBOMBS installs
 as they do not usually get installed with root privileges.

 

Clean CMake temporary files/dirs:

$ cd host/build
$ rm -rf *

 

hackrf_transfer

~/dev/hackrf$ hackrf_transfer -h
Usage:
        -h # this help
        [-d serial_number] # Serial number of desired HackRF.
        -r <filename> # Receive data into file (use '-' for stdout).
        -t <filename> # Transmit data from file (use '-' for stdin).
        -w # Receive data into file with WAV header and automatic name.
           # This is for SDR# compatibility and may not work with other software.
        [-f freq_hz] # Frequency in Hz [1MHz to 6000MHz supported, 0MHz to 7250MHz forceable].
        [-i if_freq_hz] # Intermediate Frequency (IF) in Hz [2170MHz to 2740MHz supported, 2000MHz to 3000MHz forceable].
        [-o lo_freq_hz] # Front-end Local Oscillator (LO) frequency in Hz [84MHz to 5400MHz].
        [-m image_reject] # Image rejection filter selection, 0=bypass, 1=low pass, 2=high pass.
        [-a amp_enable] # RX/TX RF amplifier 1=Enable, 0=Disable.
        [-p antenna_enable] # Antenna port power, 1=Enable, 0=Disable.
        [-l gain_db] # RX LNA (IF) gain, 0-40dB, 8dB steps
        [-g gain_db] # RX VGA (baseband) gain, 0-62dB, 2dB steps
        [-x gain_db] # TX VGA (IF) gain, 0-47dB, 1dB steps
        [-s sample_rate_hz] # Sample rate in Hz (2-20MHz supported, default 10MHz).
        [-F force] # Force use of parameters outside supported ranges.
        [-n num_samples] # Number of samples to transfer (default is unlimited).
        [-S buf_size] # Enable receive streaming with buffer size buf_size.
        [-B] # Print buffer statistics during transfer
        [-c amplitude] # CW signal source mode, amplitude 0-127 (DC value to DAC).
        [-R] # Repeat TX mode (default is off)
        [-b baseband_filter_bw_hz] # Set baseband filter bandwidth in Hz.
        Possible values: 1.75/2.5/3.5/5/5.5/6/7/8/9/10/12/14/15/20/24/28MHz, default <= 0.75 * sample_rate_hz.
        [-C ppm] # Set Internal crystal clock error in ppm.
        [-H] # Synchronize RX/TX to external trigger input.

https://github.com/greatscottgadgets/hackrf

 

GitHub - greatscottgadgets/hackrf: low cost software radio platform

low cost software radio platform. Contribute to greatscottgadgets/hackrf development by creating an account on GitHub.

github.com

 

Prerequisties for Visual Studio:

 

Download | CMake

Current development distribution Each night binaries are created as part of the testing process. Other than passing all of the tests in CMake, this version of CMake should not be expected to work in a production environment. It is being produced so that us

cmake.org

  • libusbx-1.0.18 or later
PS C:\dev\vcpkg> .\vcpkg install libusb:x64-windows

Computing installation plan...
The following packages will be built and installed:
    libusb[core]:x64-windows -> 1.0.26.11791#3
  * pkgconf[core]:x64-windows -> 1.8.0#5
  * vcpkg-msbuild[core]:x64-windows -> 2023-08-08
  * vcpkg-pkgconfig-get-modules[core]:x64-windows -> 2023-02-25
Additional packages (*) will be modified to complete this operation.
Detecting compiler hash for triplet x64-windows...
:
:
:
libusb provides CMake targets:

    find_package(libusb CONFIG REQUIRED)
    target_include_directories(main PRIVATE ${LIBUSB_INCLUDE_DIRS})
    target_link_libraries(main PRIVATE ${LIBUSB_LIBRARIES})
  • fftw-3.3.5 or later
PS C:\dev\vcpkg> .\vcpkg search fftw3
dlib[fftw3]                               fftw3 support for dlib
fftw3                    3.3.10#8         FFTW is a C subroutine library for computing the discrete Fourier transfor...
fftw3[avx]                                Builds part of the library with avx, sse2, sse
fftw3[avx2]                               Builds part of the library with avx2, fma, avx, sse2, sse
fftw3[openmp]                             Builds openmp enabled lib
fftw3[sse]                                Builds part of the library with sse
fftw3[sse2]                               Builds part of the library with sse2, sse
fftw3[threads]                            Enable threads in fftw3
matplotplusplus[fftw]                     fftw3 support for Matplot++

PS C:\dev\vcpkg> .\vcpkg install fftw3:x64-windows
Computing installation plan...
:
fftw3 provides CMake targets:

    # this is heuristically generated, and may not be correct
    find_package(FFTW3 CONFIG REQUIRED)
    target_link_libraries(main PRIVATE FFTW3::fftw3)

    find_package(FFTW3f CONFIG REQUIRED)
    target_link_libraries(main PRIVATE FFTW3::fftw3f)

    find_package(FFTW3l CONFIG REQUIRED)
    target_link_libraries(main PRIVATE FFTW3::fftw3l)
 

GitHub - GerHobbelt/pthread-win32: clone / cvs-import of pthread-win32 + local tweaks (including MSVC2008 - MSVC2022 project fil

clone / cvs-import of pthread-win32 + local tweaks (including MSVC2008 - MSVC2022 project files) - GitHub - GerHobbelt/pthread-win32: clone / cvs-import of pthread-win32 + local tweaks (including M...

github.com

cmake

hackrf\host\build> cmake ../ -G "Visual Studio 17 2022" -A x64 \
	-DLIBUSB_INCLUDE_DIR=C:\Dev\vcpkg\packages\libusb_x64-windows\include\libusb-1.0 \
    -DLIBUSB_LIBRARIES=C:\Dev\vcpkg\packages\libusb_x64-windows\lib\libusb-1.0.lib \
    -DTHREADS_PTHREADS_INCLUDE_DIR=D:\Dev\HackRF\pthread-win32 \
    -DTHREADS_PTHREADS_WIN32_LIBRARY=D:\Dev\HackRF\pthread-win32\windows\VS2022\bin\Release-Unicode-64bit-x64\pthread.lib \
    -DFFTW_INCLUDES=C:\Dev\vcpkg\packages\fftw3_x64-windows\include \
    -DFFTW_LIBRARIES=C:\Dev\vcpkg\packages\fftw3_x64-windows\lib\fftw3f.lib

CMake Deprecation Warning at CMakeLists.txt:3 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


-- Selecting Windows SDK version 10.0.22621.0 to target Windows 10.0.19045.
CMake Deprecation Warning at libhackrf/CMakeLists.txt:24 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


CMake Deprecation Warning at hackrf-tools/CMakeLists.txt:24 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


-- Configuring done
-- Generating done
-- Build files have been written to: D:/Dev/Defense/HackRF/hackrf/host/build

...

2023-08-30  02:46            18,307 ALL_BUILD.vcxproj
2023-08-30  02:06               288 ALL_BUILD.vcxproj.filters
2023-08-30  02:11               168 ALL_BUILD.vcxproj.user
2023-08-30  02:46            15,235 CMakeCache.txt
2023-08-30  02:48    <DIR>          CMakeFiles
2023-08-30  02:06             1,716 cmake_install.cmake
2023-08-30  02:06             1,486 cmake_uninstall.cmake
2023-08-30  02:46    <DIR>          hackrf-tools
2023-08-30  02:06            16,620 HackRF.sln
2023-08-30  02:06            10,139 INSTALL.vcxproj
2023-08-30  02:06               530 INSTALL.vcxproj.filters
2023-08-30  02:46    <DIR>          libhackrf
2023-08-30  02:46            19,742 uninstall.vcxproj
2023-08-30  02:06               722 uninstall.vcxproj.filters
2023-08-30  02:11    <DIR>          x64
2023-08-30  02:46            20,128 ZERO_CHECK.vcxproj
2023-08-30  02:06               531 ZERO_CHECK.vcxproj.filters

 

HackRF.sln 파일을 Microsoft Visual Studio Community 2022로 열여서 컴파일!

세 폴더에 컴파일된 파일들을 한 폴더에 모아서 사용하면 도작함!

 

TODO: pthread 까지 vcpkg로 설치해서 사용해 보면 좋을 듯

 

 

'OS > Windows' 카테고리의 다른 글

Apache Kafka  (0) 2021.10.12

https://www.tutorialspoint.com/unix/unix-io-redirections.htm

 

Unix / Linux - Shell Input/Output Redirections

Unix Linux Shell Input Output Redirections - In this chapter, we will discuss in detail about the Shell input/output redirections. Most Unix system commands take input from your terminal and send the resulting output back to your terminal. A command normal

www.tutorialspoint.com

Output Redirection

$ who > users
$ cat users
user	tty01	Sep 12 07:30
:

Example

$ echo line 1 > lines
$ cat lines
line 1
$

$ echo line 2 >> lines
$ cat lines
line 1
line 2
$

 

Input Redirection

The commands that normally take their input from the standard input can have their input redirected from a file in this manner.

For example, to count the number of lines in the file lines generated above,
you can execute the command as follows -

$ wc -l lines
2 lines
$

$ wc -l < lines
2
$

$ wc -l << EOF
> This is a simple lookup program
> for good (and bad) restaurants
> in Cape Town.
> EOF
3
$

 

Here Document

A here document is used to redirect input into an interactive shell script or program.

We can run an interactive program within a shell script without user action by supplying the required input for the interactive program, or interactive shell script.

The general form for a here document is -

command << delimiter
document
delimiter

 

Here the shell interprets the << operator as an instruction to read input until it finds a line containing the specified delimiter. All the input lines up to the line containing the delimiter are then fed into the standard input of the command.

 

The delimiter tells the shell that the here document has completed.

Without it, the shell continues to read the input forever.

The delimiter must be a single word that does not contain spaces or tabs.

 

Follwing is the input to the command wc -l to count the total number of lines -

$ wc -l << EOF
> This is a simple lookup program
> for good (and bad) restaurants
> in Cape Town.
> EOF
3
$

You can use the here document to print multiple lines using your script as follows -

#!/bin/sh

cat << EOF
This is a simple lookup program 
for good (and bad) restaurants
in Cape Town.
EOF

Result

This is a simple lookup program
for good (and bad) restaurants
in Cape Town.

 

Discard the output

Sometimes you will need to execute a command, but you don't want the output displayed on the screen.

In such cases, you can discard the output by redirecting it to the file /dev/null -

$ command > /dev/null

The file /dev/null is a special file that automatically discards all its input.

 

To discard both output of a command and its error output,
use standard redirection to redirect STDERR to STDOUT -

$ command > /dev/null 2>&1

Here 2 represents STDERR and 1 represents STDOUT.

 

You can display a message on to STDERR by redirecting STDOUT into STDERR as follows

$ echo message 1>&2

 

Redirection Commands

Sequence Command Description
1 pgm > file Output of pgm is redirected to file
2 pgm >> file Output of pgm is appeded to file
3 pgm < file Program pgm read its input from file
4 n > file Output from stream with descriptor n redirected to file
5 n >> file Output from stream with descriptor n appended to file
6 n >& m Merges output from stream n with stream m
7 n <& m Merges input from stream n with stream m
8 << tag Standard input comes from here through next tag at the start of file
9 | Takes output from one program, or process, and sends it to another

the file descriptor

  • 0 = normally standard input (STDIN)
  • 1 = standard output (STDOUT)
  • 2 = standard error output (STDERR)

'OS > Linux' 카테고리의 다른 글

Linux Shell Script  (0) 2023.08.09
LD_LIBRARY_PATH  (0) 2022.12.21
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06

에https://www.tutorialspoint.com/unix/shell_scripting.htm

 

Shell Scripting Tutorial

Shell Scripting Tutorial - A shell script is a computer program designed to be run by the Unix/Linux shell which could be one of the following:

www.tutorialspoint.com

 

기본 구조

파일명: test.sh

#!/bin/sh

echo "Hello, World"
  • 확장자: .sh
  • 첫 번째 행에 해당 쉘 명시
    • #!bin/sh
    • #!bin/bash
  • 쉘 스크립트 파일을 실행시키려면 실행 권한을 줘야 함
$ chmod 755 test.sh

실행

$ ./test.sh
or
$ sh test.sh
or
$ bash test.sh

 

기본 문법

주석(comment)

#으로 시작

 

입력/출력

  • 입력: read
  • 출력: echo
#!/bin/sh

read NAME
echo "Hello, $NAME!"

결과

$ ./test.sh
dozob
Hello, dozob!

 

※ Tip

Bash에서는 -e 플래그로 특수 문자를 escape 할 수 있음

#!bin/bash

echon -e "Hello\n$NAME!"	# 개행('\n')됨

 

Variables

  • 변수 이름으로 영문자, 숫자, 언더바('_') 사용
  • 변수에 값을 할당할 때 '='의 앞뒤에 공백이 없어야 함
  • 문자열인 경우 쌍따옴표(")로 감싸야 함
  • 변수를 사용할 때는 앞에 $를 붙임, 변수는 {}로 감쌀 수 있음
  • readonly 키워드를 앞에 붙여 읽기 전용 변수를 정의할 수 있음
  • 변수 삭제는 unset으로 가능하나 readonly 변수는 삭제 못함
#!/bin/sh

var1=1234
var2="text"

echo "var2=$var2"

readonly var3="initialized readonly variable"
var3="try to assign readonly variable"

unset var2

결과

$ ./test.sh
var2=text
./test.sh: 9: var3: is read only

 

Special Variables

변수 기능
$0 스크립트명
$1 ~ $9 N번째 인수
$# 스크립트에 전달된 인수 개수
$* 모든 인수를 모아 하나로 처리
$@ 모든 인수를 각각 처리
$? 직전에 실행한 명령(command)의 종료 값
(성공: 0, 실패: 1)
$$ 쉘 스크립트의 프로세스 ID
$! 마지막으로 실행한 백그라운드 프로세스 ID

 

Metacharacters (특수 문자)

* ? [ ] ' " \ $ ; & ( ) | ^ < > new-line space tab

문자열 내에 쓰일 때는 '\'를 앞에 붙여야 함

Sequence Quoting Description
1 Single quote All special characters between these quotes lose their special meaning.
2 Double quote Most special characters between these quotes lose their special meaning
with these exceptions -
 - $, `, \$, \', \", \\
3 Backslash Any character immediately following the backslash loses its special meaning.
4 Back quote Anything in between back quotes would be treated as a command and would be executed.

Example

#!/bin/bash

echo <-$1500.**>; (update?) [y|n]
# -bash: syntax error near unexpected token `;'
echo \<-\$1500.\*\*\>\; \(update\?\) \[y\|n\]
echo '<-$1500.**>; (update?) [y|n]'

echo 'It\'s Shell Programming
# It\s Shell Programming

echo 'It\'s Shell Programming'
# Syntax error: Unterminated quoted string

VAR=ZARA
echo "$VAR owes <-\$1500.**>; [ as of (`date +%m/%d`) ]"
# ZARA owes <-$1500.**>; [ as of (07/02) ]

 

변수 값의 치환

문법 설명
${var} 변수 값으로 치환
${var:-word} if var is null or unset, word is substitued for var.
The value of var does not change.
${var:=word} if var is null or unset, var is set to the value of word.
${var:+word} if var is set, word is substituted for var.
The value of var does not change.
${var:?message} If var is null or unset, message is printed to standard error.
This checks that variables are set correctly.
#/bin/sh

echo "1. \${var:-default value1}: \"${var:-default value1}\", var=${var}"
echo "2. \${var:=default value2}: \"${var:=default value2}\", var=${var}"

var="assigned value"
echo "var=\"assigned value\""
echo "3. \${var:+default value3}: \"${var:+default value3}\", var=${var}"
echo "4. \${var:?default value4}: \"${var:?default value4}\", var=${var}"

unset var
echo "unset var"
echo "5. \${var:+default value5}: \"${var:+default value5}\", var=${var}"
echo "6. \${var:?default value6}:"
echo " \"${var:?default value6}\", var=${var}"

결과

$ ./test.sh
1. ${var:-default value1}: "default value1", var=
2. ${var:=default value2}: "default value2", var=default value2
var="assigned value"
3. ${var:+default value3}: "default value3", var=assigned value
4. ${var:?default value4}: "assigned value", var=assigned value
unset var
5. ${var:+default value5}: "", var=
6. ${var:?default value6}:
./test.sh: line 15: var: default value6

 

Arrays

#!/bin/bash

# bash shell
ARRAY=(item item2 item3 item4)
ARRAY[0]="ITEM1"
ARRAY[2]="ITEM3"

echo "ARRAY[0]: ${ARRAY[0]}"
echo "ARRAY[2]: ${ARRAY[2]}"

echo "ARRAY[*]: ${ARRAY[*]}"
echo "ARRAY[@]: ${ARRAY[@]}"

결과

$ ./test.sh
ARRAY[0]: ITEM1
ARRAY[2]: ITEM3
ARRAY[*]: ITEM1 item2 ITEM3 item4
ARRAY[@]: ITEM1 item2 ITEM3 item4

 

Arithmetic Operators

Operator Description Example: a=10, b=20
+ Addition echo `expr $a + $b` → 30
- Substraction echo `expr $a - $b` → -10
\* (Multiplication) Multiplies values on either side of the operator echo `expr $a \* $b` → 200
/ (Division) Divide left hand operand by right hand operand echo `expr $b / $a` → 2
% (Modulus) evide left hand operand by right hand operand and returns remainder expr `expr $b % $a` → 0
= (Assignment) Aissigns right operand in left operand a=$b
== (Equality) Compares two numbers,
if both are same then returns true.
[ $a == $b ] → false
!= (Not Equality) Compares two numbers,
if both are different then return true.
[ $a != $b ] → true

※ Tip

for example, [ $a == $b ] is correct

whereas, [$a==$b] is incorrect

 

 

Relational / Boolean / String Operators

Operator Description Example
-eq equal [ $a -eq $b ]
-ne not equal [ $a -ne $b ]
-gt greater than [ $a -gt $b ]
-lt less than [ $a -lt $b ]
-ge greater than or equal to [ $a -ge $b ]
-le less than or equal to [ $a -le $b ]
Boolean Operators
! logical negation [ ! false ] → true
-o logical OR [ $a -lt 20 -o $b -gt 100 ] → true
-a logical AND [ $a -lt 20 $b -gt 100 ] → false
String Operators
= equal [ $a = $b ] → not true.
!= not equal [ $a != $b ] → true
-z Checks if the given string operand size is zero;
if it is zero length, then is returns true.
[ -z $a ] → not ture
-n Checks if the given string operand size is non-zero;
if it is nonzero length, then it returns true.
[ -n $a ] → not false
str Checks if str is not the empty string;
if it is empty, then it returns false.
[ $a ] → not false.

 

File Test Operators

Assume a variable file holds an existing file name "test" the size of which is 100 bytes and has read, write and execute permission on -

Operator Description: Checks if file ~ Example
-e file file exists; is true even if file is a directory but exists. [ -e $file ] → true
-s file file has size greater then 0 [ -s $file ] → true
     
-b file block special file [ -b $file ] → false
-c file character special file [ -c $file ] → false
-d file directory [ -d $file ] → not true
-p file named pipe [ -p $file ] → false
-f file an ordinary file as opposed to a directory or special file [ -f $file ] → true
-t file file descriptor is open and associated with a terminal [ -t $file ] → false
     
-g file has its Set Group ID (SGID) bit set [ -g $file ] → false
-k file has its Sticky bit set [ -k $file ] → false
-u file has its Set User ID (SUID) bit set [ -u $file ] → false
     
-r file readable [ -r $file ] → true
-w file writable [ -w $file ] → true
-x file executable [ -x $file ] → true

 

Decision Making

if ... else

  • if ... fi
  • if ... else ... fi
  • if ... elif ... else ... fi

 

case ... esac

  • case ... esac

case VARIABLE in CONDITION/VALUE) Command ;; esac

#!/bin/sh

DRINK="coffee"
case "$DRINK" in
    "beer") echo "맥주"
    ;;
    "juice") echo "주스"
    ;;
    "coffee") echo "커피"
    ;;
esac

 

 

Loops

  • while
  • for
  • until
  • select
while command1 ;	# this is loop1, the outer loop
do
    Statement(s) to be executed if command1 is true
    
    while command2 ;	# this is loop2, the inner loop
    do
        Statement(s) to be executed if command2 is ture
    done
    
    Statements(s) to be executed if command1 is true
done

 

Example

#!/bin/sh

a=0
while [ "$a" -lt 10 ]	# this is loop1
#until [ "$a" -ge 10 ]
do
    b="$a"
    
    while [ "$b" -ge 0 ]	# this is loop2
    #until [ "$b" -lt 0 ]
    do
        echo -n "$b "		# -n option lets echo avoid printing a new line character
        b=`expr $b - 1`
    done
    
    echo
    
    a=`expr $a + 1`
done

Result

0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0

 

Example

#!/bin/sh

for var1 in 1 2 3
do
   for var2 in 0 5
   do
      if [ $var1 -eq 2 -a $var2 -eq 0 ]
      then
         break 2
      else
         echo "$var1 $var2"
      fi
   done
done

Result

1 0
1 5

 

Example

#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "$NUM: Number is an even number!"
      continue
   fi
   echo "$NUM: Found odd number"
done

bash

#!/bin/bash

# using array
NUMS=(1 2 3 4 5 6 7)

for NUM in ${NUMS[*]}
do
   Q=`expr $NUM % 2`
   if [ $Q -eq 0 ]
   then
      echo "$NUM: Number is an even number!"
      continue
   fi
   echo "$NUM: Found odd number"
done

 

Result

1: Found odd number
2: Number is an even number!!
3: Found odd number
4: Number is an even number!!
5: Found odd number
6: Number is an even number!!
7: Found odd number

 

Substitution

Sequence Escape Description
1 \\ backslash
2 \a alert (BEL)
3 \b backspace
4 \c suppress trailing newline
5 \f form feed
6 \n new line
7 \r carriage return
8 \t horizontal tab
9 \v vertical tab

You can use the -E option to disable the interpretation of the backslash escapes (default).

You can use the -e option to enable the interpretation of the backslash escapes.

You can use the -n option to disable the insertion of a new line.

 

Command Substitution

Command substitution is the mechanism by which the shell performs a given set of commands

and then substitues their output in the place of the commands.

Syntax

`command`

When performing the command substitution make sure that you use the backquote, not the single quote character.

 

Example

#!/bin/sh

DATE=`date`
echo "Date is $DATE"

USERS=`who | wc -l`
echo "Logged in user are $USERS"

UP=`date ; uptime`
echo "Uptime is $UP"

Result

Date is Wed Aug  9 16:54:06 KST 2023
Logged in user are 0
Uptime is Wed Aug  9 16:54:06 KST 2023
 16:54:06 up 10 days, 14:15,  0 users,  load average: 0.03, 0.01, 0.00

 

'OS > Linux' 카테고리의 다른 글

Linux Shell - IO Redirections  (0) 2023.08.09
LD_LIBRARY_PATH  (0) 2022.12.21
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06

이 환경변수(environment variable)을 이용해 shared library 참조

 

$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/nvidia/deepstream/deepstream-6.1/lib

이 설정은 터미널이 닫히면 사라진다.

따라서, "~/.bashrc" 파일을 직접 수정해 줘야 함

 

.bashrc

별칭(alias)과 bash가 수행될 때 실행되는 함수를 제어하는 지역적인 시스템 설정과 관련된 파일

모든 프로그램이 실행되기 전에 수행됨

적당한 위치에 LD_LIBRARY_PATH 설정문을 넣어둔다.

 

$ nano ~/.bashrc
...
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/nvidia/deepstream/deepstream-6.1/lib
...

 

ldconfig

기본 설정 파일은 /etc/ld.so.conf

파일 내용은 아래와 같다.

include /etc/ld.so.conf.d/*.conf

추가하려는 경로는 ld.so.conf.d 디렉토리 안에 파일을 생성해서 넣으면 된다.

 

'OS > Linux' 카테고리의 다른 글

Linux Shell - IO Redirections  (0) 2023.08.09
Linux Shell Script  (0) 2023.08.09
CUDA 11.7.1 on WSL2  (0) 2022.11.13
Fastest way to check if a file exists  (0) 2022.11.10
Install libjpeg-turbo  (0) 2022.11.06

+ Recent posts