본문 바로가기

SW/ROS2 & Linux

ROS2) bashrc 파일로 alias 명령어 만들어보기

23.10.04   집필

24.02.25   1차 수정

 

--- INDEX ---

0. 잡 서론
1. .bashrc파일
2. alias 설정
3. ROS 기본 .bashrc

--- --- ---

 

0. 잡 서론

.bashrc 파일

이게 뭘까? 뭔데 ROS를 만지는데 갑자기 뜬금없이 건들일까..?

사실 ROS랑은 큰 상관은 없는데, ROS를 조몰딱 거리는데에 있어서 bashrc를 건드는게 편리하기때문에 만지작 거려봤다.

 

 

1. .bashrc 파일

bashrc는 사용자마다 run command들을 모아두는 파일인데, 여기에 다양한 단축키(alias)같은게 등록되어있다.

bash가 켜질 때 마다 이 파일을 한번 읽고 켜지므로, 실행할 파일이 많은 ROS에서는, bashrc에 기본적으로 실행 명령어들을 넣어두면, bash를 새로 여는 것 만으로도 실행 명령어들을 모조리 한번씩 읽고 시작하는 것과 같다.

 

그러니까, 짧게 말하면.. RPG게임에서 기본능력치 강화하는 스킬이 있었는데, 이를 패시브로 바꾼 느낌이다.

 

다양한 편집기들을 이용해 여기에 접속할 수 있으나(vi, gefit, vim 등), 필자는 vscode를 깔아뒀으므로 vscode를 이용해보자.

 

$ cd
$ code .

홈에서 vscode를 열면 

숨어있던 파일들이 보인다. Linux기반의 OS에서 " . "(마침표)로 시작하는 파일은 숨김파일이기 때문에 ls명령으로 보이지 않았을 것이다.

이에, .bashrc를 클릭해주면,

더보기
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
	# We have color support; assume it's compliant with Ecma-48
	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
	# a case would tend to support setf rather than setaf.)
	color_prompt=yes
    else
	color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

이런 코드가 있을텐데, 제일 마지막에 아래와 같은 코드를 추가한다.

echo "ROS2 humble has been activated"
source /opt/ros/humble/setup.bash

setup.bash는 ros2를 쓰면서 항상 돌려야되는 코드이기에, 위와 같은 코드를 추가했다.

.bashrc파일이 변경되었으므로, 

source ~/.bashrc

을 입력하여 bashrc를 다시 읽혀줘야 한다.

 

이제, 터미널을 켤 때 마다 "ROS2 humble has been activated"라는 문구가 계속 뜨게 된다.

 

 

2. alias 설정

bashrc파일에 souce로 직접적으로 넣어두면, 터미널이 켜질때마다 자동으로 ros의 setup파일이 켜지지만,

내가 따로 명령어를 만들어서 실행하고 싶을때만 간편하게 실행할 수 있다.

 

위의 1번에서 추가했던 코드 없이 아래의 코드만 넣어보자.

alias qwe="source /opt/ros/humble/setup.bash; echo \" activbated \""

그러고나서 아래의 코드를 너미널창에 입력해야 적용된다.

source ~/.bashrc

 

 

이제 qwe라는 대충만든 "명령어"가 생긴거다.

일케 된다.

 

 

3. ROS 기본 .bashrc

네이버 카페 "오로카"의 표윤석박사님 bashrc내용을 가져왔다.

일단 출처고 뭐고 다 적어놓겠지만 내가 볼려고 가져온거라... 문제시 삭제함 ㅠ

 

https://cafe.naver.com/openrt/25288

 

001 ROS 2 개발 환경 구축

Created Date: 2020.07.13 Modified Date: 2022.02.03 revision 34 * 로봇 운영체제 ROS 강좌 목차: https://cafe...

cafe.naver.com

source /opt/ros/humble/setup.bash
source ~/robot_ws/install/local_setup.bash

source /usr/share/colcon_argcomplete/hook/colcon-argcomplete.bash
source /usr/share/vcstool-completion/vcs.bash
source /usr/share/colcon_cd/function/colcon_cd.sh
export _colcon_cd_root=~/robot_ws

export ROS_DOMAIN_ID=7
export ROS_NAMESPACE=robot1

export RMW_IMPLEMENTATION=rmw_fastrtps_cpp
# export RMW_IMPLEMENTATION=rmw_connext_cpp
# export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp
# export RMW_IMPLEMENTATION=rmw_gurumdds_cpp

# export RCUTILS_CONSOLE_OUTPUT_FORMAT='[{severity} {time}] [{name}]: {message} ({function_name}() at {file_name}:{line_number})'
export RCUTILS_CONSOLE_OUTPUT_FORMAT='[{severity}]: {message}'
export RCUTILS_COLORIZED_OUTPUT=1
export RCUTILS_LOGGING_USE_STDOUT=0
export RCUTILS_LOGGING_BUFFERED_STREAM=1

alias cw='cd ~/robot_ws'
alias cs='cd ~/robot_ws/src'
alias ccd='colcon_cd'

alias cb='cd ~/robot_ws && colcon build --symlink-install'
alias cbs='colcon build --symlink-install'
alias cbp='colcon build --symlink-install --packages-select'
alias cbu='colcon build --symlink-install --packages-up-to'
alias ct='colcon test'
alias ctp='colcon test --packages-select'
alias ctr='colcon test-result'

alias rt='ros2 topic list'
alias re='ros2 topic echo'
alias rn='ros2 node list'

alias killgazebo='killall -9 gazebo & killall -9 gzserver  & killall -9 gzclient'

alias af='ament_flake8'
alias ac='ament_cpplint'

alias testpub='ros2 run demo_nodes_cpp talker'
alias testsub='ros2 run demo_nodes_cpp listener'
alias testpubimg='ros2 run image_tools cam2image'
alias testsubimg='ros2 run image_tools showimage'
[출처] 001 ROS 2 개발 환경 구축 (오픈소스 소프트웨어 & 하드웨어: 로봇 기술 공유 카페 (오로카)) | 작성자 표윤석